简体   繁体   中英

TypeError: object takes no parameters

I'm trying to create a code that utilizes the __iter__() method as a generator, but I am getting an error saying:

TypeError: object() takes no parameters.

Additionally, I am unsure whether my yield function should be called within try: or within the main() function

I am fairly new to Python and coding, so any suggestions and advice would be greatly appreciated so that I can learn. Thanks!

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

You mistyped the declaration of the __init__ method, you typed:

def __init

Instead of:

def __init__ 

Use yield for function __iter__ :

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

In your case, __iter__ maybe looks something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM