D. Lopez D. Lopez - 7 months ago 30
Python Question

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

Answer

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
Comments