python类与对象-如何使用描述符对实例属性做类型检查

如何使用描述符对实例属性做类型检查

问题举例

在某些项目中,我们实现一些类,并希望能像静态类型语言那样对它们的

实例属性做类型检查:

  p = Persosn()

  p.name = 'tom' #必须是str

  p.age = 18       #必须是int

要求:

(1)可对实例属性指定类型

(2)赋予不正确类型时抛出异常

分析

class A():
    pass

a = A()
#a.x = 'hello'
#a.__dict__['x'] = 'hello'

a.x = 'hello'等价于a.__dict__['x'] = 'hello', 需要类提供一个接口对属性所赋的值做类型检查,手动添加属性的值

解决思路

使用描述符来实现需要类型检查的属性:分别实现__get__, __set__, __delete__方法,在__set__中使用isinstance函数做类型检查

代码

class Attr:
    def __init__(self, key, type_):
        self.key = key
        self.type_ = type_

    def __set__(self, instance, value):
        print('in __set__')
        if not isinstance(value, self.type_):
            raise TypeError('must be %s' % self.type_)
        instance.__dict__[self.key] = value

    def __get__(self, instance, cls):
        print('in __get__', instance, cls)
        return instance.__dict__[self.key]

    def __delete__(self, instance):
        print('in __del__', instance)
        del instance.__dict__[self.key]

class Person:
    name = Attr('name', str)
    age = Attr('age', int)

p = Person()
p.name = 'tom'
#p.age = 20
p.age = '20'

参考资料:python3实用编程技巧进阶

猜你喜欢

转载自www.cnblogs.com/marton/p/10816512.html