Python中的魔法方法(dunder方法)是用於自定義對(duì)象行為的特殊方法。它們以雙下劃線開(kāi)頭和結(jié)尾,如__init__或__str__,並在特定語(yǔ)法或內(nèi)置函數(shù)被使用時(shí)自動(dòng)觸發(fā)。 1. __init__用於初始化對(duì)象;2. __str__和__repr__分別定義對(duì)象的可讀字符串表示和可重構(gòu)表達(dá)式;3. __add__、__sub__等定義加減等運(yùn)算行為;4. __eq__、__lt__等控制比較操作。通過(guò)實(shí)現(xiàn)這些方法,如為自定義類Point添加__add__以支持運(yùn)算,可使類的行為更自然且符合預(yù)期。使用時(shí)應(yīng)注意返回類型合理、避免修改原對(duì)象、處理錯(cuò)誤類型並保持直觀設(shè)計(jì)。
In Python, magic methods—also known as dunder methods (short for "double underscore")—are special methods that let you customize how your objects behave in various operations. These aren't meant to be called directly like regular methods; instead, they're triggered automatically when certain syntax is used or built-in functions are applied.

What makes dunder methods special?
They're surrounded by double underscores, like __init__
or __str__
, and they let you define behaviors for your objects that integrate with Python's core features. For example, when you use the
operator on two custom objects, a specific dunder method ( __add__
) is what determines how that addition works.
Commonly Used Dunder Methods
Here are some of the most frequently used ones:

Object Initialization :
__init__
– This is the constructor method, called after the object is created. It's where you usually set up your instance attributes.-
String Representation :
__str__
– Called by thestr()
function andprint()
. It should return a readable string representation of the object.
__repr__
– Called byrepr()
. Should be a valid Python expression that could recreate the object. Arithmetic Operations :
__add__
– Defines behavior for the
__sub__
– Defines behavior for the-
operator.
There are also__mul__
,__truediv__
, and more.Comparison Operators :
__eq__
– Equal (==
).
__lt__
– Less than ().<br> And others like <code>__gt__
,__le__
, etc.
These are just a few examples. Each one gives you control over how your class interacts with standard operators and functions.
How to Use Dunder Methods Effectively
Let's say you have a simple class like this:
class Point: def __init__(self, x, y): self.x = x self.y = y
If you create two instances and try to add them using
, you'll get an error. That's because Python doesn't know how to handle it unless you define __add__
.
You can fix that by adding:
def __add__(self, other): return Point(self.x other.x, self.y other.y)
Now when you do something like p1 p2
, it will work as expected and return a new Point
.
A few tips:
- Make sure the return type makes sense for your use case.
- Don't modify the original objects unless that's intentional.
- Consider handling incorrect types gracefully, maybe by returning
NotImplemented
.
Also, don't overdo it. Just because you can override behavior doesn't mean you always should. Keep things intuitive.
When Are Dunder Methods Called?
Most of the time, you won't call them directly like obj.__str__()
. Instead, Python calls them behind the scenes.
For example:
-
len(obj)
triggers__len__
-
str(obj)
triggers__str__
-
obj[key]
triggers__getitem__
Some are required if you want to support certain interfaces. Like if you want your class to work in a for
loop, you'll need to implement __iter__
and __next__
(or delegate to another iterable).
One thing to note: some dunder methods are optional. If you don't define them and someone tries to use them, Python will raise an error.
Dunder methods give you fine-grained control over how your objects interact with Python's syntax and built-in functions. They make classes feel more natural to use and help avoid clunky APIs.
Once you understand a few key ones, it becomes easier to write classes that “just work” the way users expect.
And honestly, once you've defined __repr__
or __add__
for a class, you start wondering how you ever lived without them.
基本上就這些。
以上是Python中的魔術(shù)方法是什麼?的詳細(xì)內(nèi)容。更多資訊請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

熱AI工具

Undress AI Tool
免費(fèi)脫衣圖片

Undresser.AI Undress
人工智慧驅(qū)動(dòng)的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費(fèi)的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費(fèi)的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強(qiáng)大的PHP整合開(kāi)發(fā)環(huán)境

Dreamweaver CS6
視覺(jué)化網(wǎng)頁(yè)開(kāi)發(fā)工具

SublimeText3 Mac版
神級(jí)程式碼編輯軟體(SublimeText3)

用戶語(yǔ)音輸入通過(guò)前端JavaScript的MediaRecorderAPI捕獲並發(fā)送至PHP後端;2.PHP將音頻保存為臨時(shí)文件後調(diào)用STTAPI(如Google或百度語(yǔ)音識(shí)別)轉(zhuǎn)換為文本;3.PHP將文本發(fā)送至AI服務(wù)(如OpenAIGPT)獲取智能回復(fù);4.PHP再調(diào)用TTSAPI(如百度或Google語(yǔ)音合成)將回復(fù)轉(zhuǎn)為語(yǔ)音文件;5.PHP將語(yǔ)音文件流式返回前端播放,完成交互。整個(gè)流程由PHP主導(dǎo)數(shù)據(jù)流轉(zhuǎn)與錯(cuò)誤處理,確保各環(huán)節(jié)無(wú)縫銜接。

要實(shí)現(xiàn)PHP結(jié)合AI進(jìn)行文本糾錯(cuò)與語(yǔ)法優(yōu)化,需按以下步驟操作:1.選擇適合的AI模型或API,如百度、騰訊API或開(kāi)源NLP庫(kù);2.通過(guò)PHP的curl或Guzzle調(diào)用API並處理返回結(jié)果;3.在應(yīng)用中展示糾錯(cuò)信息並允許用戶選擇是否採(cǎi)納;4.使用php-l和PHP_CodeSniffer進(jìn)行語(yǔ)法檢測(cè)與代碼優(yōu)化;5.持續(xù)收集反饋並更新模型或規(guī)則以提升效果。選擇AIAPI時(shí)應(yīng)重點(diǎn)評(píng)估準(zhǔn)確率、響應(yīng)速度、價(jià)格及對(duì)PHP的支持。代碼優(yōu)化應(yīng)遵循PSR規(guī)範(fàn)、合理使用緩存、避免循環(huán)查詢、定期審查代碼,並藉助X

使用Seaborn的jointplot可快速可視化兩個(gè)變量間的關(guān)係及各自分佈;2.基礎(chǔ)散點(diǎn)圖通過(guò)sns.jointplot(data=tips,x="total_bill",y="tip",kind="scatter")實(shí)現(xiàn),中心為散點(diǎn)圖,上下和右側(cè)顯示直方圖;3.添加回歸線和密度信息可用kind="reg",並結(jié)合marginal_kws設(shè)置邊緣圖樣式;4.數(shù)據(jù)量大時(shí)推薦kind="hex",用

要將AI情感計(jì)算技術(shù)融入PHP應(yīng)用,核心是利用雲(yún)服務(wù)AIAPI(如Google、AWS、Azure)進(jìn)行情感分析,通過(guò)HTTP請(qǐng)求發(fā)送文本並解析返回的JSON結(jié)果,將情感數(shù)據(jù)存入數(shù)據(jù)庫(kù),從而實(shí)現(xiàn)用戶反饋的自動(dòng)化處理與數(shù)據(jù)洞察。具體步驟包括:1.選擇適合的AI情感分析API,綜合考慮準(zhǔn)確性、成本、語(yǔ)言支持和集成複雜度;2.使用Guzzle或curl發(fā)送請(qǐng)求,存儲(chǔ)情感分?jǐn)?shù)、標(biāo)籤及強(qiáng)度等信息;3.構(gòu)建可視化儀錶盤,支持優(yōu)先級(jí)排序、趨勢(shì)分析、產(chǎn)品迭代方向和用戶細(xì)分;4.應(yīng)對(duì)技術(shù)挑戰(zhàn),如API調(diào)用限制、數(shù)

字符串列表可用join()方法合併,如''.join(words)得到"HelloworldfromPython";2.數(shù)字列表需先用map(str,numbers)或[str(x)forxinnumbers]轉(zhuǎn)為字符串後才能join;3.任意類型列表可直接用str()轉(zhuǎn)換為帶括號(hào)和引號(hào)的字符串,適用於調(diào)試;4.自定義格式可用生成器表達(dá)式結(jié)合join()實(shí)現(xiàn),如'|'.join(f"[{item}]"foriteminitems)輸出"[a]|[

pandas.melt()用於將寬格式數(shù)據(jù)轉(zhuǎn)為長(zhǎng)格式,答案是通過(guò)指定id_vars保留標(biāo)識(shí)列、value_vars選擇需融化的列、var_name和value_name定義新列名,1.id_vars='Name'表示Name列不變,2.value_vars=['Math','English','Science']指定要融化的列,3.var_name='Subject'設(shè)置原列名的新列名,4.value_name='Score'設(shè)置原值的新列名,最終生成包含Name、Subject和Score三列

pythoncanbeoptimizedFormized-formemory-boundoperationsbyreducingOverHeadThroughGenerator,有效dattratsures,andManagingObjectLifetimes.first,useGeneratorSInsteadoFlistSteadoflistSteadoFocessLargedAtasetSoneItematatime,desceedingingLoadeGingloadInterveringerverneDraineNterveingerverneDraineNterveInterveIntMory.second.second.second.second,Choos,Choos

安裝pyodbc:使用pipinstallpyodbc命令安裝庫(kù);2.連接SQLServer:通過(guò)pyodbc.connect()方法,使用包含DRIVER、SERVER、DATABASE、UID/PWD或Trusted_Connection的連接字符串,分別支持SQL身份驗(yàn)證或Windows身份驗(yàn)證;3.查看已安裝驅(qū)動(dòng):運(yùn)行pyodbc.drivers()並篩選含'SQLServer'的驅(qū)動(dòng)名,確保使用如'ODBCDriver17forSQLServer'等正確驅(qū)動(dòng)名稱;4.連接字符串關(guān)鍵參數(shù)
