08 __getitem__魔術(shù)方法

Python的魔法方法getitem用法: 如果類把某個(gè)屬性定義為序列,可以使用getitem()輸出序列屬性中的某個(gè)元素,或者通過(guò)迭代訪問(wèn)屬性序列中的某個(gè)元素,例如用for...in...訪問(wèn)。

class Student:
    def __init__(self,student_list):
        self.student_name = animal_list

students = Student(['Lily, 'Lucy', 'Susan'])

for student in students:
    print(student)

在用 for..in.. 迭代對(duì)象時(shí),如果對(duì)象沒有實(shí)現(xiàn) iter next 迭代器協(xié)議,Python的解釋器就會(huì)去尋找getitem 來(lái)迭代對(duì)象,如果連getitem 都沒有定義,這解釋器就會(huì)報(bào)對(duì)象不是迭代器的錯(cuò)誤:

Traceback (most recent call last):
  File "C:/Users/Phantom/Desktop/python_learning/python900集/day15/magic/method_getitem.py", line 11, in <module>
    animals = iter(animals)
TypeError: 'Student' object is not iterable

使用getitem方法后,就能夠正常迭代了。

class Student:
    def __init__(self,student_list):
        self.student_name = animal_list
    def __getitem__(self, item):
        return self.student_name[item]

students = Student(['Lily, 'Lucy', 'Susan'])

for student in students:
    print(student)

運(yùn)行結(jié)果:

dog
cat
fish
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容