引言
关于_getattr_,首先我们从一个例子入手;
class Dict(dict): def __init__(self, **kw): super().__init__(**kw) def __getattr__(self, key): try: return self[key] except KeyError: raise AttributeError(r"'Dict' object has no attribute '%s'" % key) def __setattr__(self, key, value): self[key] = value
看到里面有一个 def _getattr_(self, key):是不是不理解
概念介绍
_getattr__是python里的一个内建函数,可以很方便地动态返回一个属性;
当调用不存在的属性时,Python会试图调用__getattr__(self,'key')来获取属性,并且返回key;
class Student(object): def__getattr__(self, attrname): ifattrname =="age": return40 else: raiseAttributeError, attrname x =Student() print(x.age) #40 print(x.name) #error text omitted.....AttributeError, name
这里定义一个Student类和实例x,并没有属性age,当执行x.age,就调用_getattr_方法动态创建一个属性;
下面展示一个_getattr_经典应用的例子,可以调用dict的键值对
class ObjectDict(dict): 2 def __init__(self, *args, **kwargs): 3 super(ObjectDict, self).__init__(*args, **kwargs) 4 5 def __getattr__(self, name): 6 value = self[name] 7 if isinstance(value, dict): 8 value = ObjectDict(value) 9 return value 10 11 if __name__ == '__main__': 12 od = ObjectDict(asf={'a': 1}, d=True) 13 print od.asf, od.asf.a # {'a': 1} 1 14 print od.d # True