1 import numbers 2 from collections import abc 3 class Group: 4 #支持切片操作 5 def __init__(self, group_name, company_name, staffs): 6 self.group_name = group_name 7 self.company_name = company_name 8 self.staffs = staffs 9 10 def __reversed__(self): 11 self.staffs.reverse() 12 13 def __getitem__(self, item): 14 cls = type(self) 15 if isinstance(item, slice): 16 return cls(group_name=self.group_name, company_name=self.company_name, staffs=self.staffs[item]) 17 elif isinstance(item, numbers.Integral): 18 return cls(group_name=self.group_name, company_name=self.company_name, staffs=[self.staffs[item]]) 19 20 def __len__(self): 21 return len(self.staffs) 22 23 def __iter__(self): 24 return iter(self.staffs) 25 26 def __contains__(self, item): 27 if item in self.staffs: 28 return True 29 else: 30 return False 31 #如果key是一个整形的话就返回列表元素,如果是一个slice对象的话,就创建一个实例并返回。 32 staffs = ["bobby1", "imooc", "bobby2", "bobby3"] 33 group = Group(company_name="imooc", group_name="user", staffs=staffs) 34 reversed(group)
for循环会调用__iter__方法,返回了一个迭代器
35 for user in group:
36 print(user)
print(group[:2].staffs)
print(group[2].staffs)
会调用__getitem__方法
class _List(object): def __getitem__(self, item): print(item) I = _List() I[3] //输出:3 I[1:3]//输出:slice(1, 3, None)
本文来自博客园,作者:孙龙-程序员,转载请注明原文链接:https://www.cnblogs.com/sunlong88/articles/9384887.html