Python - 面向對象編程 - 魔術方法(雙下划線方法)


什么是魔術方法

在Python中,所有以 __ 雙下划線包起來的方法,都統稱為 Magic Method 魔術方法,也叫雙下划線方法

 

有哪些重要的魔術方法?

__new__

https://www.cnblogs.com/poloyy/p/15236309.html

 

__init__

https://www.cnblogs.com/poloyy/p/15189562.html

 

__str__

https://www.cnblogs.com/poloyy/p/15202541.html

 

__repr__

https://www.cnblogs.com/poloyy/p/15250973.html

 

__del__

https://www.cnblogs.com/poloyy/p/15192098.html

 

__call__

https://www.cnblogs.com/poloyy/p/15253366.html

 

其他比較常見的魔術方法

__len__

len() 調用對象會返回 __len__ 方法 return 的值,必須返回 integer

class A:
    def __len__(self):
        return 4


a = A()
print(len(a))


# 輸出結果
4

 

__hash__

hash() 調用對象會返回 __hash__ 方法 return 的值,必須返回 integer

# __hash__
class A:
    def __hash__(self):
        return 123456


a = A()
print(hash(a))


# 輸出結果
123456

 

__eq__

定義等於號的行為:x == y

class A:
    def __init__(self):
        self.a = 1
        self.b = 2

    def __eq__(self, obj):
        print("call eq method.")
        if self.a == obj.a and self.b == obj.b:
            return True


a = A()
b = A()
# 實例對象有 == 行為時,自動調用 __eq__() 方法
print(a == b)


# 輸出結果
call eq method.
True

 

比較操作符的魔術方法 

__lt__(self, other) 定義小於號的行為:x < y 調用 x.__lt__(y)
__le__(self, other) 定義小於等於號的行為:x <= y 調用 x.__le__(y)
__ne__(self, other) 定義不等號的行為:x != y 調用 x.__ne__(y)
__gt__(self, other) 定義大於號的行為:x > y 調用 x.__gt__(y)
__ge__(self, other) 定義大於等於號的行為:x >= y 調用 x.__ge__(y)

 

魔術方法大全

魔法方法
含義
基本的魔法方法
__new__(cls[, ...]) 1. __new__ 是在一個對象實例化的時候所調用的第一個方法
__init__(self[, ...]) 構造器,當一個實例被創建的時候調用的初始化方法
__del__(self) 析構器,當一個實例被銷毀的時候調用的方法
__call__(self[, args...]) 允許一個類的實例像函數一樣被調用:x(a, b) 調用 x.__call__(a, b)
__len__(self) 定義當被 len() 調用時的行為
__repr__(self) 定義當被 repr() 調用時的行為
__str__(self) 定義當被 str() 調用時的行為
__bytes__(self) 定義當被 bytes() 調用時的行為
__hash__(self) 定義當被 hash() 調用時的行為
__bool__(self) 定義當被 bool() 調用時的行為,應該返回 True 或 False
__format__(self, format_spec) 定義當被 format() 調用時的行為
 有關屬性
__getattr__(self, name) 定義當用戶試圖獲取一個不存在的屬性時的行為
__getattribute__(self, name) 定義當該類的屬性被訪問時的行為
__setattr__(self, name, value) 定義當一個屬性被設置時的行為
__delattr__(self, name) 定義當一個屬性被刪除時的行為
__dir__(self) 定義當 dir() 被調用時的行為
__get__(self, instance, owner) 定義當描述符的值被取得時的行為
__set__(self, instance, value) 定義當描述符的值被改變時的行為
__delete__(self, instance) 定義當描述符的值被刪除時的行為
 比較操作符
__lt__(self, other) 定義小於號的行為:x < y 調用 x.__lt__(y)
__le__(self, other) 定義小於等於號的行為:x <= y 調用 x.__le__(y)
__eq__(self, other) 定義等於號的行為:x == y 調用 x.__eq__(y)
__ne__(self, other) 定義不等號的行為:x != y 調用 x.__ne__(y)
__gt__(self, other) 定義大於號的行為:x > y 調用 x.__gt__(y)
__ge__(self, other) 定義大於等於號的行為:x >= y 調用 x.__ge__(y)
 算數運算符
__add__(self, other) 定義加法的行為:+
__sub__(self, other) 定義減法的行為:-
__mul__(self, other) 定義乘法的行為:*
__truediv__(self, other) 定義真除法的行為:/
__floordiv__(self, other) 定義整數除法的行為://
__mod__(self, other) 定義取模算法的行為:%
__divmod__(self, other) 定義當被 divmod() 調用時的行為
__pow__(self, other[, modulo]) 定義當被 power() 調用或 ** 運算時的行為
__lshift__(self, other) 定義按位左移位的行為:<<
__rshift__(self, other) 定義按位右移位的行為:>>
__and__(self, other) 定義按位與操作的行為:&
__xor__(self, other) 定義按位異或操作的行為:^
__or__(self, other) 定義按位或操作的行為:|
                       反運算
__radd__(self, other) (與上方相同,當左操作數不支持相應的操作時被調用)
__rsub__(self, other) (與上方相同,當左操作數不支持相應的操作時被調用)
__rmul__(self, other) (與上方相同,當左操作數不支持相應的操作時被調用)
__rtruediv__(self, other) (與上方相同,當左操作數不支持相應的操作時被調用)
__rfloordiv__(self, other) (與上方相同,當左操作數不支持相應的操作時被調用)
__rmod__(self, other) (與上方相同,當左操作數不支持相應的操作時被調用)
__rdivmod__(self, other) (與上方相同,當左操作數不支持相應的操作時被調用)
__rpow__(self, other) (與上方相同,當左操作數不支持相應的操作時被調用)
__rlshift__(self, other) (與上方相同,當左操作數不支持相應的操作時被調用)
__rrshift__(self, other) (與上方相同,當左操作數不支持相應的操作時被調用)
__rand__(self, other) (與上方相同,當左操作數不支持相應的操作時被調用)
__rxor__(self, other) (與上方相同,當左操作數不支持相應的操作時被調用)
__ror__(self, other) (與上方相同,當左操作數不支持相應的操作時被調用)
增量賦值運算
__iadd__(self, other) 定義賦值加法的行為:+=
__isub__(self, other) 定義賦值減法的行為:-=
__imul__(self, other) 定義賦值乘法的行為:*=
__itruediv__(self, other) 定義賦值真除法的行為:/=
__ifloordiv__(self, other) 定義賦值整數除法的行為://=
__imod__(self, other) 定義賦值取模算法的行為:%=
__ipow__(self, other[, modulo]) 定義賦值冪運算的行為:**=
__ilshift__(self, other) 定義賦值按位左移位的行為:<<=
__irshift__(self, other) 定義賦值按位右移位的行為:>>=
__iand__(self, other) 定義賦值按位與操作的行為:&=
__ixor__(self, other) 定義賦值按位異或操作的行為:^=
__ior__(self, other) 定義賦值按位或操作的行為:|=
 一元操作符
__pos__(self) 定義正號的行為:+x
__neg__(self) 定義負號的行為:-x
__abs__(self) 定義當被 abs() 調用時的行為
__invert__(self) 定義按位求反的行為:~x
 類型轉換
__complex__(self) 定義當被 complex() 調用時的行為(需要返回恰當的值)
__int__(self) 定義當被 int() 調用時的行為(需要返回恰當的值)
__float__(self) 定義當被 float() 調用時的行為(需要返回恰當的值)
__round__(self[, n]) 定義當被 round() 調用時的行為(需要返回恰當的值)
__index__(self) 1. 當對象是被應用在切片表達式中時,實現整形強制轉換
2. 如果你定義了一個可能在切片時用到的定制的數值型,你應該定義 __index__
3. 如果 __index__ 被定義,則 __int__ 也需要被定義,且返回相同的值
上下文管理(with 語句)
__enter__(self) 1. 定義當使用 with 語句時的初始化行為
2. __enter__ 的返回值被 with 語句的目標或者 as 后的名字綁定
__exit__(self, exc_type, exc_value, traceback) 1. 定義當一個代碼塊被執行或者終止后上下文管理器應該做什么
2. 一般被用來處理異常,清除工作或者做一些代碼塊執行完畢之后的日常工作
 容器類型
__len__(self) 定義當被 len() 調用時的行為(返回容器中元素的個數)
__getitem__(self, key) 定義獲取容器中指定元素的行為,相當於 self[key]
__setitem__(self, key, value) 定義設置容器中指定元素的行為,相當於 self[key] = value
__delitem__(self, key) 定義刪除容器中指定元素的行為,相當於 del self[key]
__iter__(self) 定義當迭代容器中的元素的行為
__reversed__(self) 定義當被 reversed() 調用時的行為
__contains__(self, item) 定義當使用成員測試運算符(in 或 not in)時的行為

回頭再用到哪些再詳解吧

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM