为什么 __iter__ 返回 self ?

问题描述

iter 所做的就是返回自我。这如何将类(PowTwo)的实例(数字)变成可迭代的?

class PowTwo:

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


numbers = PowTwo(3)

i = iter(numbers)

print(next(i))
print(next(i))
print(next(i))
print(next(i))
print(next(i))

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)