标签:迭代 结果 pre python类 init for循环 函数 存在 pytho
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__把类变成了序列,所以可切片可遍历
标签:迭代 结果 pre python类 init for循环 函数 存在 pytho
原文地址:https://www.cnblogs.com/raind/p/10099521.html