一文帶你深入理解Python魔法方法
一、構(gòu)造和初始化
__new__
和 __init__
是 Python 對(duì)象生命周期的開始。__new__
方法是在一個(gè)對(duì)象實(shí)例化的時(shí)候所調(diào)用的第一個(gè)方法,在調(diào)用 __init__
初始化前,先調(diào)用 __new__
。
class MyClass: def __new__(cls, *args, **kwargs): print('Instance is created') instance = super().__new__(cls) return instance def __init__(self, name): print('Instance is initialized') self.name = name obj = MyClass('MyClass') # 輸出:Instance is created Instance is initialized
二、字符串表示
__str__
和 __repr__
都是用于顯示的魔法方法。__str__
是友好易讀的方式呈現(xiàn),而 __repr__
是準(zhǔn)確、無(wú)歧義地表達(dá)出來(lái),主要供開發(fā)和調(diào)試時(shí)使用。
class MyClass: def __init__(self, name): self.name = name def __str__(self): return f'Instance of MyClass with name {self.name}' def __repr__(self): return f'MyClass(name={self.name})' obj = MyClass('MyClass') print(str(obj)) # 輸出:Instance of MyClass with name MyClass print(repr(obj)) # 輸出:MyClass(name=MyClass)
三、算術(shù)運(yùn)算符
魔法方法還可以用來(lái)定義對(duì)象的算術(shù)運(yùn)算行為,例如 __add__
、__sub__
、__mul__
等。
class Number: def __init__(self, value): self.value = value def __add__(self, other): return self.value + other.value num1 = Number(1) num2 = Number(2) print(num1 + num2) # 輸出:3
四、比較運(yùn)算符
比較運(yùn)算符的魔法方法包括 __lt__
、__le__
、__eq__
、__ne__
、__gt__
、__ge__
等。
class Number: def __init__(self, value): self.value = value def __lt__(self, other): return self.value < other.value num1 = Number(1) num2 = Number(2) print(num1 < num2) # 輸出:True
五、屬性訪問(wèn)
當(dāng)我們?cè)噲D訪問(wèn)一個(gè)對(duì)象的屬性時(shí),__getattr__
、__setattr__
、__delattr__
和 __getattribute__
魔法方法就會(huì)被調(diào)用。__getattribute__
方法是用于獲取一個(gè)屬性的值,而 __setattr__
是在我們?cè)噲D設(shè)置一個(gè)屬性值時(shí)被調(diào)用。
class MyClass: def __init__(self): self.name = 'MyClass' def __getattribute__(self, item): if item == 'name': print('Accessing name attribute') return object.__getattribute__(self, item) def __setattr__(self, key, value): print(f'Setting attribute {key} with value {value}') self.__dict__[key] = value obj = MyClass() print(obj.name) # 輸出:Accessing name attribute MyClass obj.name = 'New name' # 輸出:Setting attribute name with value New name
六、上下文管理器
上下文管理器是通過(guò) __enter__
和 __exit__
魔法方法實(shí)現(xiàn)的,它們通常在 with
語(yǔ)句中使用。
class ManagedFile: def __init__(self, filename): self.filename = filename def __enter__(self): self.file = open(self.filename, 'r') return self.file def __exit__(self, exc_type, exc_val, exc_tb): if self.file: self.file.close() with ManagedFile('hello.txt') as f: content = f.read() print(content)
在這個(gè)例子中,__enter__
方法打開文件并返回,__exit__
方法在離開 with
塊時(shí)被調(diào)用,負(fù)責(zé)關(guān)閉文件。
七、結(jié)論
Python 的魔法方法為我們提供了改變對(duì)象行為的強(qiáng)大工具,讓我們能夠以符合 Python 風(fēng)格的方式去操作和處理對(duì)象。同時(shí),理解并掌握這些魔法方法也是成為高級(jí) Python 程序員的必經(jīng)之路。
到此這篇關(guān)于一文帶你深入理解Python魔法方法的文章就介紹到這了,更多相關(guān)Python魔法方法內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python 編碼Basic Auth使用方法簡(jiǎn)單實(shí)例
這篇文章主要介紹了 Python 編碼Basic Auth使用方法簡(jiǎn)單實(shí)例的相關(guān)資料,需要的朋友可以參考下2017-05-05PyCharm Terminal終端命令行Shell設(shè)置方式
這篇文章主要介紹了PyCharm Terminal終端命令行Shell設(shè)置方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-01-01PyQT5 QTableView顯示綁定數(shù)據(jù)的實(shí)例詳解
今天小編就為大家分享一篇PyQT5 QTableView顯示綁定數(shù)據(jù)的實(shí)例詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-06-06Python實(shí)現(xiàn)常見坐標(biāo)系的相互轉(zhuǎn)換
WGS84坐標(biāo)系、GCJ02坐標(biāo)系、BD09坐標(biāo)系和Web?墨卡托投影坐標(biāo)系是我們常見的四個(gè)坐標(biāo)系。這篇文章為大家整理了這四個(gè)坐標(biāo)系之間相互轉(zhuǎn)換的方法,需要的可以參考一下2023-02-02pycharm設(shè)置python文件模板信息過(guò)程圖解
這篇文章主要介紹了pycharm設(shè)置python文件模板信息過(guò)程圖解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-03-03解讀torch.cuda.amp自動(dòng)混合精度訓(xùn)練之節(jié)省顯存并加快推理速度
這篇文章主要介紹了torch.cuda.amp自動(dòng)混合精度訓(xùn)練之節(jié)省顯存并加快推理速度問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-08-08用Python實(shí)現(xiàn)一個(gè)模仿UP主彈幕控制的直播間功能
up主通過(guò)代碼實(shí)現(xiàn)了實(shí)時(shí)讀取直播間里的彈幕內(nèi)容,進(jìn)而控制自己的電腦,把彈幕翻譯成指令操控《賽博朋克2077》游戲,這篇文章主要介紹了用Python實(shí)現(xiàn)一個(gè)模仿UP主彈幕控制的直播間功能,需要的朋友可以參考下2021-12-12Python3實(shí)現(xiàn)從指定路徑查找文件的方法
這篇文章主要介紹了Python3實(shí)現(xiàn)從指定路徑查找文件的方法,涉及Python目錄與文件的相關(guān)操作技巧,需要的朋友可以參考下2015-05-05