python魔法函数(二)之__getitem__、__len__、__iter__

魔法函数会增强python类的类型,独立存在
__getitem
class Company:
    def __init__(self, employees):
        self.employees = employees

    def __getitem__(self, item):
        return self.employees[item]


company = Company(['a', 'b', 'c'])
for val in company:
    print(val)
company1 = company[:2]
for val in company1:
    print(val)

结果:
a
b
c
a
b
for循环迭代时,如果对象不具有iterator接口,就会调用类的__getitem__魔法函数(前提是定义了),上述的__getitem__把类变成了序列,所以可切片可遍历
len

len()方法是为了能让class作用于len()函数。

iter

如果一个类想被用于for ... in循环,类似list或tuple那样,就必须实现一个__iter__()方法,该方法返回一个迭代对象,然后,Python的for循环就会不断调用该迭代对象的__next__()方法拿到循环的下一个值,直到遇到StopIteration错误时退出循环。

原文地址:https://www.cnblogs.com/raind/p/10099521.html