class PowTwo:
"""Class to implement an iterator
of powers of two"""
def __init__(self, max=0):
self.max = max
def __iter__(self):
self.n = 0
return self
def __next__(self):
if self.n <= self.max:
result = 2 ** self.n
self.n += 1
return result
else:
raise StopIteration
a = PowTwo(3)
b = iter(a)
print(next(a))
Run Code Online (Sandbox Code Playgroud)
没有这个片段b = iter(a),输出是
Traceback (most recent call last):
File "/Users/Mark/test2.py", line 20, in <module>
print(next(a))
File "/Users/Mark/test2.py", line 13, in __next__
if self.n <= self.max:
AttributeError: 'PowTwo' object …Run Code Online (Sandbox Code Playgroud)