在类中使用局部变量来确定下一个变量的使用时间:
class P():
i = 0
def __init__(self, n0):
self.i=n0-1
self.n = n0
def __iter__(self):
return self
def __next__(self):
self.i=self.i-1
if self.i == 1:
raise StopIteration
num = self.n
self.n = self.n // 2 if self.n % 2 == 0 else 3 * self.n + 1
return num
nmax = 10
PP = P(nmax)
PPP = []
for j in PP:
PPP.append(j)
print(PPP)
注意:通常写下以下内容更安全:
if self.i <= 1:
然后
if self.i == 1:
.在未来的一些变化中,你可能会改变
i
,然后开始用2递减,然后
==
变种将失败。