python(Class6)

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


__get__, __set__, __delete__


# 含有以下方法中的一个的类叫做描述符
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)

p1 = Person()
p1.name = 'Bob'
print(p1.name)
p1.age = 17
print(p1.age)

你可能感兴趣的:(python(Class6))