l = list("hello") #这就是在做实例化,list是一个类
for i in l: #先将一个对象执行__iter__()
print(i)
#迭代器协议:通过__iter__将一个对象变成可迭代对象,再调用__next__()方法进行迭代下一项
class Foo:
def __init__(self,n):
self.n = n
def __iter__(self):
return self
def __next__(self):
if self.n == 13:
raise StopIteration("终止了")
self.n += 1
return self.n
f1 = Foo(10)
# print(f1.__next__())
# print(f1.__next__())
# print(f1.__next__())
# print(f1.__next__())
for x in f1:print(x) #for循环会抓捕到结束的异常,然后终止
#斐波那契数列:下一个值是上两个值的和。如1,2,3,5,8
class Fib:
def __init__(self,m,n):
self.m = m
self.n = n
def __iter__(self):
return self
def __next__(self):
if self.m > 100:
raise StopIteration("终止")
self.m,self.n = self.n,self.m+self.n
return self.m
fb1 = Fib(1,2)
print(fb1.__next__())
for z in fb1:print(z)