Python中的Dunder方法實(shí)現(xiàn)小結(jié)
?? 今日知識(shí)點(diǎn)
- 核心主題:深入理解Python中的dunder(魔術(shù))方法
- 適用場(chǎng)景:面向?qū)ο缶幊獭⒆远x類行為、提升代碼可讀性
?? 什么是Dunder方法?
Dunder方法(Double Underscore Methods)是Python中以雙下劃線開頭和結(jié)尾的特殊方法,例如 __init__、__str__ 等。它們?cè)试S我們自定義類的行為,讓對(duì)象支持運(yùn)算符、打印、迭代等功能。
?? 核心Dunder方法分類與示例
1. 初始化與銷毀
__init__(self, ...)
用途:對(duì)象創(chuàng)建時(shí)自動(dòng)調(diào)用,用于初始化屬性。
class Student:
? ? def __init__(self, name, score):
? ? ? ? self.name = name
? ? ? ? self.score = score
s = Student("張三", 95)
print(s.name) ?# 輸出: 張三
__del__(self)
用途:對(duì)象銷毀前調(diào)用,可用于清理資源。
class FileHandler:
? ? def __del__(self):
? ? ? ? print("文件句柄已釋放")
2. 字符串表示
__str__(self)
用途:定義 print(obj) 或 str(obj) 的輸出。
class Car:
? ? def __init__(self, brand):
? ? ? ? self.brand = brand
? ? def __str__(self):
? ? ? ? return f"汽車品牌: {self.brand}"
car = Car("特斯拉")
print(car) ?# 輸出: 汽車品牌: 特斯拉
__repr__(self)
用途:開發(fā)者調(diào)試時(shí)顯示的內(nèi)容,建議返回可重構(gòu)對(duì)象的表達(dá)式。
def __repr__(self):
? ? return f'Car("{self.brand}")'
3. 運(yùn)算符重載
__add__(self, other)
用途:定義 + 運(yùn)算符的行為。
class Vector: ? ? def __init__(self, x, y): ? ? ? ? self.x = x ? ? ? ? self.y = y ? ? def __add__(self, other): ? ? ? ? return Vector(self.x + other.x, self.y + other.y) v1 = Vector(1, 2) v2 = Vector(3, 4) v3 = v1 + v2 print(v3.x, v3.y) ?# 輸出: 4 6
__eq__(self, other)
用途:定義 == 比較邏輯。
def __eq__(self, other): ? ? return self.x == other.x and self.y == other.y
4. 容器行為
__len__(self)
用途:支持 len(obj)。
class MyList: ? ? def __init__(self, data): ? ? ? ? self.data = data ? def __len__(self): ? ? ? ? return len(self.data) ml = MyList([1, 2, 3]) print(len(ml)) ?# 輸出: 3
__getitem__(self, key)
用途:支持 obj[key] 訪問。
def __getitem__(self, index): ? ? return self.data[index]
5. 可調(diào)用對(duì)象
__call__(self, ...)
用途:讓實(shí)例可以像函數(shù)一樣被調(diào)用。
class Multiplier: ? ? def __init__(self, factor): ? ? ? ? self.factor = factor ? ? def __call__(self, x): ? ? ? ? return x * self.factor double = Multiplier(2) print(double(5)) ?# 輸出: 10
?? 實(shí)戰(zhàn)案例:自定義分?jǐn)?shù)類
class Fraction:
? ? def __init__(self, numerator, denominator):
? ? ? ? self.numerator = numerator
? ? ? ? self.denominator = denominator
? ? def __str__(self):
? ? ? ? return f"{self.numerator}/{self.denominator}"
? ? def __add__(self, other):
? ? ? ? new_num = self.numerator * other.denominator + other.numerator * self.denominator
? ? ? ? new_den = self.denominator * other.denominator
? ? ? ? return Fraction(new_num, new_den)
f1 = Fraction(1, 2)
f2 = Fraction(1, 3)
result = f1 + f2
print(result) ?# 輸出: 5/6
? 注意事項(xiàng)
- 不要濫用dunder方法,保持代碼清晰易懂
- 遵循Python慣例,避免自定義非標(biāo)準(zhǔn)的dunder方法
- 測(cè)試邊界條件,確保方法行為符合預(yù)期
?? 小貼士
- 學(xué)會(huì)閱讀官方文檔了解經(jīng)常使用的dunder方法
- 利用IDE提示快速查找相關(guān)方法
- 多實(shí)踐,從簡(jiǎn)單類開始逐步掌握復(fù)雜用法
到此這篇關(guān)于Python中的Dunder方法實(shí)現(xiàn)小結(jié)的文章就介紹到這了,更多相關(guān)Python Dunder方法內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python實(shí)現(xiàn)網(wǎng)站表單提交和模板
今天小編就為大家分享一篇關(guān)于Python實(shí)現(xiàn)網(wǎng)站表單提交和模板,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2019-01-01
一文搞懂霍夫曼樹原理及C++/Python/Java實(shí)戰(zhàn)實(shí)現(xiàn)
霍夫曼樹是一種用于數(shù)據(jù)壓縮的樹形結(jié)構(gòu),通過構(gòu)建具有最小帶權(quán)路徑長(zhǎng)度的二叉樹,實(shí)現(xiàn)高效的數(shù)據(jù)編碼,這篇文章主要介紹了霍夫曼樹原理及C++/Python/Java實(shí)戰(zhàn)實(shí)現(xiàn)的相關(guān)資料,需要的朋友可以參考下2025-11-11
python?共現(xiàn)矩陣的實(shí)現(xiàn)代碼
這篇文章主要介紹了python?共現(xiàn)矩陣的實(shí)現(xiàn)代碼,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07
Python+OpenCV編寫車輛計(jì)數(shù)器系統(tǒng)
本文,我們將使用歐幾里德距離跟蹤和輪廓的概念在 Python 中使用 OpenCV 構(gòu)建車輛計(jì)數(shù)器系統(tǒng),文中的示例代碼講解詳細(xì),感興趣的可以了解一下2022-05-05
如何基于python實(shí)現(xiàn)單目三維重建詳解
單目三維重建是根據(jù)單個(gè)攝像頭的運(yùn)動(dòng)模擬雙目視覺獲得物體在空間中的三維視覺信息,下面這篇文章主要給大家介紹了關(guān)于如何基于python實(shí)現(xiàn)單目三維重建的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-06-06
Python中使用?zipfile創(chuàng)建文件壓縮工具
這篇文章主要介紹了Python中使用zipfile創(chuàng)建文件壓縮工具,通過使用 wxPython 模塊,我們創(chuàng)建了一個(gè)簡(jiǎn)單而實(shí)用的文件壓縮工具,本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的ca參考借鑒價(jià)值,需要的朋友可以參考下2023-09-09

