簡體   English   中英

迭代器 Class 不遞增值 Python

[英]Iterator Class Not Incrementing Value Python

我正在使用迭代器 class 來生成幾何級數。 當我編譯代碼時,它運行了正確的次數,但我的迭代器的值並沒有從第一個值改變。 例如,如果我輸入 5 作為項數,2 作為第一項,3 作為共同比率,程序將 output 2 5 次。 我搞砸了什么?

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始終為 1(在__next__的頂部)

1-0 總是零

任何提高到零的東西都是 1 (@ self.d**(i-1) )

所以你最終得到self.i = self.i * 1

但是正如對這個答案和原始問題的評論所指出的那樣......你還有其他問題......但這就是為什么self.i在你調用_next_()時沒有增加

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM