Python的__getattr__方法学习
生活随笔
收集整理的這篇文章主要介紹了
Python的__getattr__方法学习
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
__getattr__函數的作用: 如果屬性查找(attribute lookup)在實例以及對應的類中(通過__dict__)失敗, 那么會調用到類的__getattr__函數;
如果沒有定義這個函數,那么拋出AttributeError異常。由此可見,__getattr__一定是作用于屬性查找的最后一步
舉個栗子:
class A(object):def __init__(self, a, b):self.a1 = aself.b1 = bprint('init')def mydefault(self, *args):print('default:' + str(args[0]))def __getattr__(self, name):print("other fn:", name)return self.mydefaulta1 = A(10, 20) a1.fn1(33) a1.fn2('hello')運行結果:
init other fn: fn1 default:33 other fn: fn2 default:hello第16行調用fn1屬性時,查找不到次屬性,程序調用__getattr__方法
用__getattr__方法可以處理調用屬性異常
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:778463939 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' class Student(object):def __getattr__(self, attrname):if attrname == "age":return 'age:40'else:raise AttributeError(attrname)x = Student() print(x.age) # 40 print(x.name)這里定義一個Student類和實例x,并沒有屬性age,當執行x.age,就調用_getattr_方法動態創建一個屬性,執行x.name時,__getattr__方法沒有對其處理,拋出異常
age:40File "XXXX.py", line 10, in <module>print(x.name)File "XXXX.py", line 6, in __getattr__raise AttributeError(attrname) AttributeError: name下面展示一個_getattr_經典應用的例子,可以調用dict的鍵值對
class ObjectDict(dict):def __init__(self, *args, **kwargs):super(ObjectDict, self).__init__(*args, **kwargs)def __getattr__(self, name):value = self[name]if isinstance(value, dict):value = ObjectDict(value)return valueif __name__ == '__main__':od = ObjectDict(asf = {'a': 1}, d = True)print(od.asf, od.asf.a) # {'a': 1} 1print(od.d) # True總結
以上是生活随笔為你收集整理的Python的__getattr__方法学习的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python 文件writelines(
- 下一篇: Python的小括号( )、中括号[ ]