Lorenz
Lorenz

Reputation: 306

Call a method in an outer object from an inner object

Class A instantiates an object from Class B as a member variable. How can this class B object call methods from the Class A object? When I execute the program below I would expect to get a "Hello" printed, but I get an error instead saying "name 'a' is not defined"

What is the issue here and how can I fix it?

class B:
    def __init__(self):
        a.say_hello()

class A:
    other = None

    def __init__(self):
        self.other = B()

    def say_hello():
        print("Helo")

a = A()

Upvotes: 0

Views: 28

Answers (1)

Silvio Mayolo
Silvio Mayolo

Reputation: 70297

Python references are one-way. You'll need to retain a reference in the reverse direction for this to work.

class B:
    def __init__(self, outer):
        outer.say_hello()

class A:
    # other = None # (see below)

    def __init__(self):
        self.other = B(self)

    def say_hello():
        print("Helo")

a = A()

If you need outer for more than just the constructor, you can store it in an instance variable.

You also don't need the other = None line. In Python, you don't need to declare your instance variables at the top of the class like you do in Java or C++. Instead, you just use self. to assign to them and they start existing. other = None in that scope makes a class variable, similar to static variable in Java, that can be referenced by A.other (Note the capital A; this is the class itself, not an instance of it).

There are situations where you might want to declare instance variables at the top of the class in some form or another (__slots__ and PEP 484 annotations are the main two), but for simple classes when you're starting out, it's not necessary, and an assignment like that will not do what you expect.

Upvotes: 1

Related Questions