Python的getattr函數(shù)方法學(xué)習(xí)使用示例
正文
__getattr__函數(shù)的作用: 如果屬性查找(attribute lookup)在實例以及對應(yīng)的類中(通過__dict__)失敗, 那么會調(diào)用到類的__getattr__函數(shù);
如果沒有定義這個函數(shù),那么拋出AttributeError異常。由此可見,__getattr__一定是作用于屬性查找的最后一步
舉個栗子:
class A(object): def __init__(self, a, b): self.a1 = a self.b1 = b print('init') def mydefault(self, *args): print('default:' + str(args[0])) def __getattr__(self, name): print("other fn:", name) return self.mydefault a1 = A(10, 20) a1.fn1(33) a1.fn2('hello')
運行結(jié)果:
init
other fn: fn1
default:33
other fn: fn2
default:hello
第16行調(diào)用fn1屬性時,查找不到次屬性,程序調(diào)用__getattr__方法
用__getattr__方法可以處理調(diào)用屬性異常
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,當(dāng)執(zhí)行x.age,就調(diào)用_getattr_方法動態(tài)創(chuàng)建一個屬性,執(zhí)行x.name時,__getattr__方法沒有對其處理,拋出異常
age:40 File "XXXX.py", line 10, in <module> print(x.name) File "XXXX.py", line 6, in __getattr__ raise AttributeError(attrname) AttributeError: name
下面展示一個_getattr_經(jīng)典應(yīng)用的例子,可以調(diào)用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 value if __name__ == '__main__': od = ObjectDict(asf = {'a': 1}, d = True) print(od.asf, od.asf.a) # {'a': 1} 1 print(od.d) # True
以上就是Python的getattr方法學(xué)習(xí)使用示例的詳細內(nèi)容,更多關(guān)于Python getattr方法的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
詳解Python如何循環(huán)遍歷Numpy中的Array
Numpy是Python中常見的數(shù)據(jù)處理庫,是數(shù)據(jù)科學(xué)中經(jīng)常使用的庫。在本文中,我們將學(xué)習(xí)如何迭代遍歷訪問矩陣中的元素,需要的可以參考一下2022-04-04Pandas的DataFrame如何做交集,并集,差集與對稱差集
這篇文章主要介紹了Pandas的DataFrame如何做交集,并集,差集與對稱差集,Python的數(shù)據(jù)類型集合由不同元素組成的集合,集合中是一組無序排列的可?Hash?的值,可以作為字典的Key,下面來看看文章的詳細內(nèi)容吧2022-01-01python:刪除離群值操作(每一行為一類數(shù)據(jù))
這篇文章主要介紹了python:刪除離群值操作(每一行為一類數(shù)據(jù)),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06基于Python socket實現(xiàn)簡易網(wǎng)絡(luò)聊天室
本文主要介紹了基于Python socket實現(xiàn)簡易網(wǎng)絡(luò)聊天室,本文將通過pyqt5作為桌面應(yīng)用框架,socket作為網(wǎng)絡(luò)編程的框架,從而實現(xiàn)包括客戶端和服務(wù)端的網(wǎng)絡(luò)聊天室的GUI應(yīng)用,需要的可以參考一下2022-07-07