python魔法方法之__setattr__()
前言:
python提供了諸多的魔法方法,其中__setattr__()方法主要用于類實例進行屬性賦值,其定義在Object類官方提供的說明如下:
Called when an attribute assignment is attempted.
This is called instead of the normal mechanism (i.e. store the value in the instance dictionary).
name is the attribute name, value is the value to be assigned to it.
簡單的說,__setattr__()在屬性賦值時被調用,并且將值存儲到實例字典中,這個字典應該是self的__dict__屬性。即:在類實例的每個屬性進行賦值時,都會首先調用__setattr__()方法,并在__setattr__()方法中將屬性名和屬性值添加到類實例的__dict__屬性中。
1、實例屬性管理__dict__
下面的測試代碼中定義了三個實例屬性,每個實例屬性注冊后都print()
此時的__dict__
,
代碼如下:
class AnotherFun: ? ? def __init__(self): ? ? ? ? self.name = "Liu" ? ? ? ? print(self.__dict__) ? ? ? ? self.age = 12 ? ? ? ? print(self.__dict__) ? ? ? ? self.male = True ? ? ? ? print(self.__dict__) another_fun = AnotherFun()
得到的結果顯示出,每次實例屬性賦值時,都會將屬性名和對應值存儲到__dict__字典中:
{'name': 'Liu'} {'name': 'Liu', 'age': 12} {'name': 'Liu', 'age': 12, 'male': True}
2、__setattr__()與__dict__
由于每次類實例進行屬性賦值時都會調用__setattr__()
,所以可以重載__setattr__()方法,來動態(tài)的觀察每次實例屬性賦值時__dict__()的變化。下面的Fun類重載了__setattr__()方法,并且將實例的屬性和屬性值作為__dict__的鍵-值對:
class Fun: ? ? def __init__(self): ? ? ? ? self.name = "Liu" ? ? ? ? self.age = 12 ? ? ? ? self.male = True ? ? ? ?? ? ? def __setattr__(self, key, value): ? ? ? ? print("*"*50) ? ? ? ? print("setting:{}, ?with:{}".format(key[], value)) ? ? ? ? print("current __dict__ : {}".format(self.__dict__)) ? ? ? ? # 屬性注冊 ? ? ? ? self.__dict__[key] = value fun = Fun() ? ?
通過在__setattr__()中將屬性名作為key,并將屬性值作為value,添加到了__dict__中,得到的結果如下:
**************************************************
setting:name, with:Liu
current __dict__ : {}
**************************************************
setting:age, with:12
current __dict__ : {'name': 'Liu'}
**************************************************
setting:male, with:True
current __dict__ : {'name': 'Liu', 'age': 12}
可以看出,__init__()中三個屬性賦值時,每次都會調用一次__setattr__()
函數(shù)。
3、重載__setattr__()必須謹慎
由于__setattr__()
負責在__dict__中對屬性進行注冊,所以自己在重載時必須進行屬性注冊過程,下面是__setattr__()不進行屬性注冊的例子:
class NotFun: ? ? def __init__(self): ? ? ? ? self.name = "Liu" ? ? ? ? self.age = 12 ? ? ? ? self.male = True ? ?? ? ? def __setattr__(self, key, value): ? ? ? ? pass not_fun = NotFun() print(not_fun.name)
由于__setattr__中并沒有將屬性注冊到__dict__中,所以not_fun對象并沒有name屬性,因此最后的print(not_fun.name)會報出屬性不存在的錯誤:
AttributeError Traceback (most recent call last)
<ipython-input-21-6158d7aaef71> in <module>()
8 pass
9 not_fun = NotFun()
---> 10 print(not_fun.name)AttributeError: 'NotFun' object has no attribute 'name'
所以,重載__setattr__時必須要考慮是否在__dict__中進行屬性注冊。
總結:
python的實例屬性的定義、獲取和管理可以通過__setattr__()和__dict__配合進行,當然還有對應的__getattr__()方法,本文暫時不做分析。__setattr__()方法在類的屬性賦值時被調用,并通常需要把屬性名和屬性值存儲到self的__dict__字典中。
到此這篇關于python魔法方法之__setattr__()的文章就介紹到這了,更多相關python魔法內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
利用python將xml文件解析成html文件的實現(xiàn)方法
下面小編就為大家分享一篇利用python將xml文件解析成html文件的實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2017-12-12python學習之panda數(shù)據(jù)分析核心支持庫
這篇文章主要給大家介紹了關于python學習之panda數(shù)據(jù)分析核心支持庫的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-05-05使用python實現(xiàn)excel的Vlookup功能
這篇文章主要介紹了使用python實現(xiàn)excel的Vlookup功能,當我們想要查找的數(shù)據(jù)量較大時,這時則有請我們的主角VLookup函數(shù)出場,那么如何用python實現(xiàn)VLookup呢,需要的朋友可以參考下2023-04-04Pytorch搭建yolo3目標檢測平臺實現(xiàn)源碼
這篇文章主要為大家介紹了Pytorch搭建yolo3目標檢測平臺實現(xiàn)源碼,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-05-05