簡體   English   中英

TypeError:對象不帶參數

[英]TypeError: object takes no parameters

我正在嘗試創建一個使用__iter__()方法作為生成器的代碼,但出現一條錯誤消息:

TypeError:object()不接受任何參數。

另外,我不確定是否應該在try:或main()函數中調用我的yield函數

我對Python和編碼還很陌生,所以任何建議和建議都將不勝感激,以便我學習。 謝謝!

class Counter(object):

    def __init__(self, filename, characters):
        self._characters = characters
        self.index = -1

        self.list = []
        f = open(filename, 'r')
        for word in f.read().split():
            n = word.strip('!?.,;:()$%')
            n_r = n.rstrip()
            if len(n) == self._characters:
                self.list.append(n)

    def __iter(self):
        return self

    def next(self):
        try:
            self.index += 1
            yield self.list[self.index]

            except IndexError:
                raise StopIteration
            f.close()

if __name__ == "__main__":
    for word in Counter('agency.txt', 11):
        print "%s' " % word

您輸錯了__init__方法的聲明,您輸了:

def __init

代替:

def __init__ 

對函數__iter__使用yield

class A(object):
    def __init__(self, count):
        self.count = count

    def __iter__(self):
        for i in range(self.count):
            yield i

for i in A(10):
    print i

在您的情況下, __iter__可能看起來像這樣:

def __iter__(self):
    for i in self.list:
        yield i

暫無
暫無

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

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