Python.__getitem__方法

Python的魔法方法__getitem__ 可以让对象实现迭代功能,这样就可以使用for…in… 来迭代该对象了
如果不定义__getitem__方法时,运行下列代码会提示错误:

class person:
    def __init__(self, name_list):
        self.person_name = name_list

persons = person(["张三","李四","王五","赵六"])
for person in persons.person_name:
    print(person)

输出:

TypeError: 'person' object is not iterable

当添加了__getitem__方法后,程序运行正常,原因是在迭代对象时,如果对象不是可迭代的类型,Python的解释器就会去寻找__getitem__方法来迭代对象:

class person:
    def __init__(self, name_list):
        self.person_name = name_list

    def __getitem__(self, index):
        return self.person_name[index]

persons = person(["张三","李四","王五","赵六"])
for person in persons:
    print(person)

输出:

张三
李四
王五
赵六

当然,如果没有定义__getitem__ 方法,还想正常迭代对象,则可以这样修改程序,输出结果同样正确:

class person:
    def __init__(self, name_list):
        self.person_name = name_list

persons = person(["张三","李四","王五","赵六"])
for person in persons.person_name:
    print(person)

你可能感兴趣的:(Python)