python属性查找顺序
1 import numbers 2 3 class IntField: 4 # 数据描述符 5 def __get__(self, instance, owner): 6 return self.value 7 8 def __set__(self, instance, value): 9 if not isinstance(value, numbers.Integral): 10 raise ValueError('int value need') 11 if value < 0: 12 raise ValueError('positive value need') 13 self.value = value 14 15 def __delete__(self, instance): 16 pass 17 18 class NonDataIntField: 19 # 非数据属性描述符 20 def __get__(self, instance, owner): 21 return self.value 22 23 class User: 24 # age = IntField() 25 age = NonDataIntField() 26 27 if __name__=='__main__': 28 user = User() 29 user.__dict__['age'] = 'abc' 30 print(user.__dict__) 31 print(getattr(user, 'age'))
输出:
{'age': 'abc'} abc
查找顺序:
先查找__getattribute__:
1.查找数据描述符__get__
2.查找实例__dict__
3.查找基类
若是非数据描述符访问其__get__
否则查找基类__dict__
没找到再查找__getattr__
否则抛出异常AttributeError
Talk is cheap, show my code to you.