为什么在这段代码中改变了变量 a?

Pyt*_*bie -1 python scope python-3.x

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 has no attribute 'n'
Run Code Online (Sandbox Code Playgroud)

我的问题:

b = iter(a)我没有使用a = iter(a). 这里怎么改变变量a?

use*_*ica 6

__iter__是可变的:它将对象的n属性设置为0. 这是您代码中唯一的初始化n。如果__iter__没有被调用,它在__next__寻找n时不会找到。

可变__iter__方法是一个坏主意。您应该在__init__.