Python中的Dunder方法實現(xiàn)小結(jié)
?? 今日知識點
- 核心主題:深入理解Python中的dunder(魔術(shù))方法
- 適用場景:面向?qū)ο缶幊?、自定義類行為、提升代碼可讀性
?? 什么是Dunder方法?
Dunder方法(Double Underscore Methods)是Python中以雙下劃線開頭和結(jié)尾的特殊方法,例如 __init__、__str__ 等。它們允許我們自定義類的行為,讓對象支持運算符、打印、迭代等功能。
?? 核心Dunder方法分類與示例
1. 初始化與銷毀
__init__(self, ...)
用途:對象創(chuàng)建時自動調(diào)用,用于初始化屬性。
class Student:
? ? def __init__(self, name, score):
? ? ? ? self.name = name
? ? ? ? self.score = score
s = Student("張三", 95)
print(s.name) ?# 輸出: 張三
__del__(self)
用途:對象銷毀前調(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)試時顯示的內(nèi)容,建議返回可重構(gòu)對象的表達式。
def __repr__(self):
? ? return f'Car("{self.brand}")'
3. 運算符重載
__add__(self, other)
用途:定義 + 運算符的行為。
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)用對象
__call__(self, ...)
用途:讓實例可以像函數(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
?? 實戰(zhà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
? 注意事項
- 不要濫用dunder方法,保持代碼清晰易懂
- 遵循Python慣例,避免自定義非標準的dunder方法
- 測試邊界條件,確保方法行為符合預期
?? 小貼士
- 學會閱讀官方文檔了解經(jīng)常使用的dunder方法
- 利用IDE提示快速查找相關(guān)方法
- 多實踐,從簡單類開始逐步掌握復雜用法
到此這篇關(guān)于Python中的Dunder方法實現(xiàn)小結(jié)的文章就介紹到這了,更多相關(guān)Python Dunder方法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
一文搞懂霍夫曼樹原理及C++/Python/Java實戰(zhàn)實現(xiàn)
霍夫曼樹是一種用于數(shù)據(jù)壓縮的樹形結(jié)構(gòu),通過構(gòu)建具有最小帶權(quán)路徑長度的二叉樹,實現(xiàn)高效的數(shù)據(jù)編碼,這篇文章主要介紹了霍夫曼樹原理及C++/Python/Java實戰(zhàn)實現(xiàn)的相關(guān)資料,需要的朋友可以參考下2025-11-11
Python+OpenCV編寫車輛計數(shù)器系統(tǒng)
本文,我們將使用歐幾里德距離跟蹤和輪廓的概念在 Python 中使用 OpenCV 構(gòu)建車輛計數(shù)器系統(tǒng),文中的示例代碼講解詳細,感興趣的可以了解一下2022-05-05
Python中使用?zipfile創(chuàng)建文件壓縮工具
這篇文章主要介紹了Python中使用zipfile創(chuàng)建文件壓縮工具,通過使用 wxPython 模塊,我們創(chuàng)建了一個簡單而實用的文件壓縮工具,本文結(jié)合實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的ca參考借鑒價值,需要的朋友可以參考下2023-09-09

