引言
關於_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