class fls(object):#创建一个类,继承于object
def __init__(self, val, times):#初始化val,times
self.val = val
self.count = times
def __getitem__(self, n):#调用了python中__getitem__方法,相当于通过n可以查找相应的value.
if n >= self.count:
raise IndexError("Object has no item %s %n")
return self.val
thing = fls("*", 5)#实例化fls
for c in thing:#c和5比较,如果小就返回*,这里for循环可以遍历thing实例,是因为调用了__getitem__内置函数
print(c)#打印*
thing = fls(120, 3)
for c in thing:
print(c)
python代码分析04
最新推荐文章于 2024-07-12 14:00:11 发布