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

Jackey Python 630 次浏览 没有评论
# 如何使用描述符对实例属性做类型检查
class Descriptor(object):
    def __get__(self, instance, owner):
        print('in __get__', instance, owner)

    def __set__(self, instance, value):
        print('in __set__')

    def __delete__(self, instance):
        print('in __delete__')


class A(object):
    x = Descriptor()


a = A()
a.x
A.x

a.x = 5

del a.x


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

    def __get__(self, instance, owner):
        return instance.__dict__[self.name]

    def __set__(self, instance, value):
        if not isinstance(value, self.type_):
            raise TypeError('expected an %s' % self.type_)
        instance.__dict__[self.name] = value

    def __delete__(self, instance):
        del instance.__dict__[self.name]


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


p = Person()
p.name = 'Bob'
# p.age = '17'
print(p.name)

 

发表评论

您的电子邮箱地址不会被公开。

Go