1. 程式人生 > >魔法函式__len__ ,__getitem_

魔法函式__len__ ,__getitem_

魔法函式是可以提高效能的, 應該直接走的直譯器。裡面做了好多優化。廢話少說,先來段程式碼再做解釋。

class Person:
    def __init__(self,persion_list):
        self.persion_list=persion_list
    def __getitem__(self, item):
        return self.persion_list[item]
    def __len__(self):
        return len(self.persion_list)
body=Person(["Xiuwu","Adny","Maggie"])

for i in body:
    print (i)
print(body[0])

print(len(body))

列印的結果如下:

C:\Users\tengfei\PycharmProjects\test1\venv\Scripts\python.exe C:/Users/tengfei/PycharmProjects/test1/alert.py
Xiuwu
Adny
Maggie
Xiuwu
3

Process finished with exit code 0

魔法函式 是 獨立的函式,不依賴任何類,但是任何類都可以 直接呼叫,加強類的使用,,格式為 雙下劃線開頭和結尾, 系統會自認為直接呼叫,不需要寫呼叫方法, 比如 def getitem (self,item):

  1. return self.person_list[item] 這個 魔法函式如果放在 類裡面, 會直接找 Person屬性, item會自增加 直到找不到報錯結束, 使用的時候 直接 類的例項 做for迴圈,就可以了, 不需要用 例項再呼叫屬性,因為魔法函式已經替你完成了這一步。 運用好魔法函式,可以節省時間,程式碼明瞭。
    2.如果我登出下邊的函式, 再去呼叫len(body),看看效果如何:
 #def __len__(self):
    #    return len(self.persion_list)
報錯如下:
Adny
Maggie
Xiuwu
Traceback (most recent call last):
  File "C:/Users/tengfei/PycharmProjects/test1/alert.py", line 14, in <module>
    print(len(body))
TypeError: object of type 'Person' has no len()

通過以上報錯很明顯是 ,Person 這個類的物件那個沒有對應的方法,len() 實際只是適合dict,list 等形式,這個適合如果還是想直接區,必須重寫len 的方法, 如上邊的程式碼,直接返回len(self.person_list).