[英]Iterator Class Not Incrementing Value Python
I am using an Iterator class to generate a geometric progression.我正在使用迭代器 class 来生成几何级数。 When I compile the code it runs the correct number of times but the value of my iterator does not change from the first value.当我编译代码时,它运行了正确的次数,但我的迭代器的值并没有从第一个值改变。 For example if I input 5 for the number of terms, 2 for the first term, and 3 for the common ratio the program will output 2 five times.例如,如果我输入 5 作为项数,2 作为第一项,3 作为共同比率,程序将 output 2 5 次。 What have I messed up?我搞砸了什么?
class geo_p:
def __init__(self, n):
self.a = int(input('Enter the first term:'))
self.d = int(input('Enter the common ratio:'))
self.i = self.a
self.n = n
def _iter_(self):
return self
def _next_(self):
i = 1
if i < self.n:
#sets curr = to the current term in progression
current = self.i
self.i = (self.i * (self.d**(i-1)))
i +=1
return current
else:
raise StopIteration()
y = geo_p
n = int(input('Enter the number of terms: '))
y.__init__(y, n)
print(y)
for i in range (n):
print(y._next_(y))
i
is always 1 (at the top of __next__
) i
始终为 1(在__next__
的顶部)
1-0 is always zero 1-0 总是零
anything raised to the zero is 1 (@ self.d**(i-1)
)任何提高到零的东西都是 1 (@ self.d**(i-1)
)
so you end up with self.i = self.i * 1
所以你最终得到self.i = self.i * 1
but as the comments on this answer and the original question point out... you have other issues... but this is why self.i
is not incrementing when you call _next_()
但是正如对这个答案和原始问题的评论所指出的那样......你还有其他问题......但这就是为什么self.i
在你调用_next_()
时没有增加
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.