使用描述符多实例属性做类型检查
1 class Attr(object): 2 3 def __init__(self, name, type_): 4 self.name = name 5 self.type_ = type_ 6 7 def __get__(self, instance, cls): 8 return instance.__dict__[self.name] 9 10 def __set__(self, instance, value): 11 if not isinstance(value, self.type_): 12 raise TypeError('expected an %s'% self.type_) 13 14 instance.__dict__[self.name] = value 15 16 def __delete__(self, instance): 17 del instance.__dict__[self.name] 18 19 20 21 class Person(object): 22 name = Attr('name', str) 23 age = Attr('age', int) 24 height = Attr('height', float) 25 26 27 28 p = Person() 29 p.name = 'ray' 30 print(p.name)