TypeError: object takes no parameters

TypeError: object takes no parameters

我正在尝试创建一个使用 __iter__() 方法作为生成器的代码,但我收到一条错误消息:

TypeError: object() takes no parameters.

此外,我不确定我的 yield 函数是应该在 try: 中调用还是在 main() 函数中调用

我对 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