垃圾回收 | Python從入門到精通:高階篇之三十五
特殊方法
特殊方法,也稱為魔術方法。
特殊方法都是使用__開頭和結尾的。例如: __init__、__del__。
特殊方法一般不需要我們手動調用,需要在一些特殊情況下自動執行。
我們去
官方文檔去找一下。
我們接下來學習一些特殊方法。
定義一個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)
執行結果:
列印一個元組:
t = 1,2,3
print(t)
可以發現兩個的執行結果不一緻,是因為當我們列印一個對象時,實際上列印的是對象的中特殊方法__str__()的傳回值。
__str__():
我們通過代碼來看一下:
def __str__(self):
return 'Hello Person'
print(p1)
print(p2)
執行結果:、

此時我們發現列印的結果是沒有意義的,想要像元組一樣輸出對象中的資訊,我們需要修改傳回值:
def __str__(self):
return 'Person [name=%s , age=%d]'%(self.name,self.age)
__str__()這個特殊方法會在嘗試将對象轉換為字元串的時候調用,它的作用可以用來指定對象轉換為字元串的結果 (print函數)。
與__str__()類似的還有__repr__()。
__repr__():
通過代碼來看一下:
def __repr__(self):
return 'Hello'
print(repr(p1))
__repr__()這個特殊方法會在對目前對象使用repr()函數時調用,它的作用是指定對象在 ‘互動模式’中直接輸出的效果。
比較大小:
直接執行結果
print(p1 > p2)
通過執行結果來看,我們需要解決的是如何支援大于、小于、等于這些運算符。
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)
可以發現,如果直接傳回True,不管怎麼比較都是True,這是有問題的。
此時修改傳回值代碼:
return self.age > other.age
__gt__會在對象做大于比較的時候調用,該方法的傳回值将會作為比較的結果。他需要兩個參數,一個self表示目前對象,other表示和目前對象比較的對象。簡單來說:
self > other
。
__len__():擷取對象的長度
object.__bool__(self)
def __bool__(self):
return self.age > 17
print(bool(p1))
修改p1的age:
p1 = Person('孫悟空',8)
此時先将p1的age修改為之前的。
我們可以通過bool來指定對象轉換為布爾值的情況。
我們來看一下:
if p1 :
print(p1.name,'已經成年了')
else :
print(p1.name,'還未成年了')
此時再去将年齡修改為8:
另外還有一些對對象的運算:
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學習站