一文帶你深入理解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)確、無歧義地表達(dá)出來,主要供開發(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)算符
魔法方法還可以用來定義對(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五、屬性訪問
當(dāng)我們?cè)噲D訪問一個(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六、上下文管理器
上下文管理器是通過 __enter__ 和 __exit__ 魔法方法實(shí)現(xiàn)的,它們通常在 with 語句中使用。
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操作mysql實(shí)現(xiàn)一個(gè)超市管理系統(tǒng)
超市管理系統(tǒng)有管理員和普通用戶兩條分支,只需掌握Python基礎(chǔ)語法,就可以完成這個(gè)項(xiàng)目,下面這篇文章主要給大家介紹了關(guān)于python操作mysql實(shí)現(xiàn)一個(gè)超市管理系統(tǒng)的相關(guān)資料,需要的朋友可以參考下2022-12-12
基于python 將列表作為參數(shù)傳入函數(shù)時(shí)的測(cè)試與理解
這篇文章主要介紹了基于python 將列表作為參數(shù)傳入函數(shù)時(shí)的測(cè)試與理解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-06-06
flask的orm框架SQLAlchemy查詢實(shí)現(xiàn)解析
這篇文章主要介紹了flask的orm框架SQLAlchemy查詢實(shí)現(xiàn)解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-12-12
解決使用pycharm提交代碼時(shí)沖突之后文件丟失找回的方法
這篇文章主要介紹了解決使用pycharm提交代碼時(shí)沖突之后文件丟失找回的方法 ,需要的朋友可以參考下2018-08-08
python游戲庫pygame經(jīng)典教程(推薦!)
Python Pygame是一款專門為開發(fā)和設(shè)計(jì) 2D 電子游戲而生的軟件包,是入門級(jí)游戲開發(fā)庫,下面這篇文章主要給大家介紹了python游戲庫pygame經(jīng)典教程的相關(guān)資料,需要的朋友可以參考下2022-12-12
在linux系統(tǒng)中安裝python3.8.1?并卸載?python3.6.2?更新python3引導(dǎo)到3.8.1的
這篇文章主要介紹了如何在linux系統(tǒng)中安裝python3.8.1?并卸載?python3.6.2?更新python3引導(dǎo)到3.8.1,本文分步驟給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-11-11
Python Web Flask擴(kuò)展開發(fā)指南分享
這篇文章主要介紹了Python Web Flask擴(kuò)展開發(fā)指南,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2025-05-05

