【发布时间】:2020-07-09 20:15:37
【问题描述】:
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))
没有这个sn-p 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 has no attribute 'n'
我的问题:
b = iter(a)我没有使用a = iter(a)。变量a怎么在这里变了?
【问题讨论】:
-
__iter__返回self。我不确定是什么绊倒了你。请澄清。 -
@MadPhysicist,我不明白的是我将 iter() 函数应用于变量 a 并将其分配给变量 b。但是,变量 a 在这个过程中也获得了这个 self.n 属性。我希望它保持不变。
-
您可以将同一个对象分配给多个名称。它仍然是同一个对象。
-
@MadPhysicist,因此,iter(a) 只是将 self.n 属性添加到对象和对象 ID 保持不变?
-
是的。我会立即添加一个答案
标签: python python-3.x scope