1

I'm trying to call the instance method of objects inside a dictionary who have the objects themselves, all are from the same class. But i have a infinite recursion, i think that 'self' doesn't change and reference the first object all the time.

class Foo():
    name = 'name'
    foo_objects = {}
    def print_name(self):
        output = self.name
        for key, value in self.foo_objects.items():
            output += value.print_name()
        return output

I'm using it like this:

def main():
    foo = Foo()
    foo.foo_objects['key'] = Foo()
    print foo.print_name()

if __name__ == '__main__':
    sys.exit(main())

And i get this error:

  ...etc...
    output += value.print_name()
  File "C:\dev\python\projects\test\test.py", line 41, in print_name
    output += value.print_name()
  File "C:\dev\python\projects\test\test.py", line 41, in print_name
    output += value.print_name()
RuntimeError: maximum recursion depth exceeded

What´s wrong? What I'm not understanding of python recursion? How can be do? Thanks for any help, and excuse me my bad english.

1 Answer 1

4

You've defined name and foo_objects as class variables, not instance variables -- i.e. they are currently shared between all instances of the Foo class.

Change:

class Foo():
  name = 'name'
  foo_objects = {}
...

to:

class Foo():
  def __init__(self):
    self.name = 'name'
    self.foo_objects = {}
...

and they will become instance variables as I suspect you wanted them to be.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks!!, Now i know about class attributes and instance attributes in python.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.