小编Pyt*_*bie的帖子

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

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)

python scope python-3.x

-1
推荐指数
1
解决办法
60
查看次数

标签 统计

python ×1

python-3.x ×1

scope ×1