Python 3.x 如何为循环打印在类中找到的有效值
/*国际热核实验堆(iter)或下一个(iter)的品脱是多少 我尝试了str(iter(self.n)),但是得到了NameError:name'self'没有定义*/Python 3.x 如何为循环打印在类中找到的有效值,python-3.x,Python 3.x,/*国际热核实验堆(iter)或下一个(iter)的品脱是多少 我尝试了str(iter(self.n)),但是得到了NameError:name'self'没有定义*/ class PowTwo: def __init__(self, max = 0): self.max = max # def __iter__(self): self.n = 1 return self # def __next__(self):
class PowTwo:
def __init__(self, max = 0):
self.max = max
#
def __iter__(self):
self.n = 1
return self
#
def __next__(self):
if self.n <= self.max:
result = 2 ** self.n
self.n += 1
return result
else:
raise StopIteration
#
# How do you print self.n in __iter__ or __next__
#
for item in PowTwo(4):
print("Self.n: " + str(iter(self.n)) + " Item = Result: " + str(item))
第二类:
定义初始值(自,最大值=0):
self.max=max
#
定义(自我):
self.n=1
回归自我
#
定义下一个(自我):
如果self.n你的意思是这样的
p = PowTwo(4)
it = iter(p)
while True:
try:
# get the next item
print(it.n,next(it))
except StopIteration:
# if StopIteration is raised, break from loop
break
#1 2
#2 4
#3 8
#4 16
你是说像这样的
p = PowTwo(4)
it = iter(p)
while True:
try:
# get the next item
print(it.n,next(it))
except StopIteration:
# if StopIteration is raised, break from loop
break
#1 2
#2 4
#3 8
#4 16
您需要先将实例保存在变量中:
powtow = PowTow(4)
for item in powtow:
print("Self.n: " + powtow.n + " Item = Result: " + str(item))
在Python 3.8中,可以少写一行:
for item in powtow := PowTow(4):
print("Self.n: " + powtow.n + " Item = Result: " + str(item))
但在此之前,表达式中不允许赋值。您需要先将实例保存在变量中:
powtow = PowTow(4)
for item in powtow:
print("Self.n: " + powtow.n + " Item = Result: " + str(item))
在Python 3.8中,可以少写一行:
for item in powtow := PowTow(4):
print("Self.n: " + powtow.n + " Item = Result: " + str(item))
但在此之前,表达式中不允许赋值