開發與維運

特殊方法 | Python從入門到精通:高階篇之三十六

垃圾回收 | Python從入門到精通:高階篇之三十五

特殊方法

特殊方法,也稱為魔術方法。
特殊方法都是使用__開頭和結尾的。例如: __init__、__del__。
特殊方法一般不需要我們手動調用,需要在一些特殊情況下自動執行。
我們去官方文檔去找一下。

image.png
image.png

我們接下來學習一些特殊方法。
定義一個Person類:

class Person(object):
    """人類"""
    def __init__(self, name , age):
        self.name = name
        self.age = age

# 創建兩個Person類的實例        
p1 = Person('孫悟空',18)
p2 = Person('豬八戒',28)

# 打印p1
print(p1)

執行結果:

image.png

打印一個元組:

t = 1,2,3
print(t)

執行結果:

image.png

可以發現兩個的執行結果不一致,是因為當我們打印一個對象時,實際上打印的是對象的中特殊方法__str__()的返回值。

__str__():
我們通過代碼來看一下:

    def __str__(self):
        return 'Hello Person'   
 
 print(p1)  
  print(p2)  

執行結果:、

image.png

此時我們發現打印的結果是沒有意義的,想要像元組一樣輸出對象中的信息,我們需要修改返回值:

    def __str__(self):
        return 'Person [name=%s , age=%d]'%(self.name,self.age) 

執行結果:

image.png

__str__()這個特殊方法會在嘗試將對象轉換為字符串的時候調用,它的作用可以用來指定對象轉換為字符串的結果 (print函數)。
與__str__()類似的還有__repr__()。

__repr__():
通過代碼來看一下:

    def __repr__(self):
        return 'Hello'   

print(repr(p1))

執行結果:

image.png

__repr__()這個特殊方法會在對當前對象使用repr()函數時調用,它的作用是指定對象在 ‘交互模式’中直接輸出的效果。
比較大小:
直接執行結果

print(p1 > p2)

image.png

通過執行結果來看,我們需要解決的是如何支持大於、小於、等於這些運算符。

object.__lt__(self, other)    #  小於 <
object.__le__(self, other)   # 小於等於 <=
object.__eq__(self, other)     # 等於 ==
object.__ne__(self, other)    # 不等於 !=
object.__gt__(self, other)     # 大於 >
object.__ge__(self, other)    # 大於等於 >= 

我們來演示一下:

    def __gt__(self , other):
        return True

print(p1 > p2)
print(p2 > p1)

執行結果:

image.png

可以發現,如果直接返回True,不管怎麼比較都是True,這是有問題的。
此時修改返回值代碼:

        return self.age > other.age

執行結果:

image.png

__gt__會在對象做大於比較的時候調用,該方法的返回值將會作為比較的結果。他需要兩個參數,一個self表示當前對象,other表示和當前對象比較的對象。簡單來說:self > other

__len__():獲取對象的長度

object.__bool__(self)

    def __bool__(self):
        return self.age > 17

print(bool(p1))

執行結果:

image.png

修改p1的age:

p1 = Person('孫悟空',8)

執行結果:

image.png

此時先將p1的age修改為之前的。
我們可以通過bool來指定對象轉換為布爾值的情況。
我們來看一下:

if p1 :
    print(p1.name,'已經成年了')
else :
    print(p1.name,'還未成年了')

執行結果:

image.png

此時再去將年齡修改為8:
執行結果:

image.png

另外還有一些對對象的運算:

object.__add__(self, other)  
object.__sub__(self, other)   
object.__mul__(self, other)   
object.__matmul__(self, other)   
object.__truediv__(self, other)    
object.__floordiv__(self, other)   
object.__mod__(self, other)    
object.__divmod__(self, other)   
object.__pow__(self, other[, modulo])   
object.__lshift__(self, other)   
object.__rshift__(self, other)   
object.__and__(self, other)     
object.__xor__(self, other)      
object.__or__(self, other)      

我們在需要的時候去調用就可以了。這些方法都是對多態的體現。

配套視頻課程,點擊這裡查看

獲取更多資源請訂閱Python學習站

Leave a Reply

Your email address will not be published. Required fields are marked *