python魔法方法,也稱為dunder方法(“雙重下劃線”方法的簡短)是特殊的方法,它們以雙重底漆( __
)啟動和結尾。它們提供了一種根據內置操作員和功能來定制對象和類的行為的方法。這些方法不是由程序員直接調用的。取而代之的是,當在類的對像上執行某些操作時,Python解釋器暗示它們。例如,當您使用
操作員一起添加兩個對象時,python內部檢查這些對象的類是否定義了 __添加__
魔術方法。如果是這樣,該方法被稱為執行添加。否則,將提出 typeerror
。這些方法允許您定義自定義類與Python的核心功能相互作用,從而使代碼更加直觀和Pythonic。它們從本質上擴展了內置運算符的功能和功能,可以與您自己的自定義數據結構無縫合作。名稱“ dunder”是一種口語化,是由圍繞其名稱的雙重下劃線而引起的。
通過使用特定的魔術方法來實現Python中的操作員超載。每個操作員都有一個相應的魔術方法,該方法定義了將其應用於自定義類的對象時的行為。例如:
__添加__(self,其他)
:超載
operator。此方法將 self
(類的實例)和其他
(正在添加的對象)作為參數。它應該返回加法的結果。
__ sub __(self,helf,其他)
:超載 -
operator。 (自我,其他):超載/
運算符。 __ floordiv __(self,self,其他)
:超載 // code> //
coper>運算符(地板disemander) /code>操作員(模型)。
**
operator(opentiation) li> __ LE __(自我,其他)
:超載< =
操作員(少於或等於)。
:
超載> =
操作員(大於或等於)。!=
操作員(不等於)。
示例:
<pre class="brush:php;toolbar:false"> <pre class="brush:php;toolbar:false"> <pre class="brush:php;toolbar:false"> <pre class="brush:php;toolbar:false"> <code class="“" python> class vector:def __init __init __(self,x,x = x = x = x self.y = y def __自我________________________________________________自行車自身自身) __str __(self):返回f&quot'vector({self.x},{self.y})&quot; v1 =向量(1,2)v2 =向量(3,4)v3 = v1 v2 print(v3)#輸出:vector(4,6)</code>
在此示例中, __添加__
方法> code> code> code> code> vector code> code> code> obsects。請注意,您通常需要同時定義添加和 radd 用於完整操作員超載的方法。 radd 處理您的自定義對象位於操作員右側的情況。其他運營商也存在類似的對。
魔術方法對於構建強大和直覺的類別至關重要。 Here are some common use cases:
__str__(self)
and __repr__(self)
control how objects are displayed when printed or converted to strings. __str__
should provide a user-friendly representation, while __repr__
should be unambiguous and suitable for debugging.__iter__(self)
and __next__(self)
allow you to create iterable objects, enabling the use of for
loops on your custom classes.__enter__(self)
and __exit__(self)
are used with the with
statement for managing resources (eg, file handling, database connections).__getattr__(self, name)
and __setattr__(self, name, value)
allow you to customize how attributes are accessed and modified.__eq__
, __lt__
, __gt__
, etc., enable you to define how your objects compare to each other.__len__
, __getitem__
, __setitem__
allow you to implement custom collections that behave like lists, dictionaries, etc.While many magic methods exist, some are more fundamental for creating well-behaved custom classes:
__init__(self, ...)
: The constructor, essential for initializing object attributes.__str__(self)
and/or __repr__(self)
: Provide human-readable and unambiguous string representations of your objects.__eq__(self, other)
: Crucial for defining equality between objects of your class.__len__(self)
: Necessary if your class represents a collection, allowing you to use the len()
function.These four are often the minimum required to make a custom class behave in a predictable and user-friendly manner.添加其他魔術方法取決於您要實現的特定功能,但是這四個功能為在Python中創建精心設計的類提供了堅實的基礎。
以上是什麼是Python魔法方法(Dunder方法)?的詳細內容。更多資訊請關注PHP中文網其他相關文章!