魔法函数会增强python类的类型,独立存在
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__把类变成了序列,所以可切片可遍历
原文地址:https://www.cnblogs.com/raind/p/10099521.html
时间: 2024-10-25 03:07:29