Home > other >  How to access parent class instance attribute from child class instance?
How to access parent class instance attribute from child class instance?

Time:09-17

How to access the Parent's name in this example?

class Parent:
    def __init__(self) :
        self.name = "toto"
        self.enfant = self.Child()

    class Child:
        def __init__(self) :
            self.child_name="tata"

        def affiche(self):
            print(?? Parent.name) # how to display the parent's name ?

CodePudding user response:

You can't do it the way you would in Java. Nested classes in Python are completely independent objects. They live without any knowledge of their parent, and in fact, can't see their parent when the class body is being executed.

The solution to your problem is to reference the parent in the child (also, don't bother nesting classes):

class Child:
    def __init__(self, parent):
        self.child_name = "tata"
        self.parent = parent
        
    def affiche(self):
        print(self.parent.name)

class Parent:
    def __init__(self) :
        self.name = "toto"
        self.enfants = [Child()]

If you were to nest Child into Parent, you would still write it the same way, and call the constructor as self.Child(self).


You may want to look at the following questions for more information:

CodePudding user response:

As I said in a comment, there's no special relationship between your two classes other than the fact the definition of one is nested in the namespace of the other. In order to do what you want, you'll need to explicitly "tell" the Child class who its parent is by passing it as an argument when constructing an instance of one — and it will need to explicitly save that value if it wants to use it later in some other method like affiche().

Here's what I mean:

class Parent:
    def __init__(self) :
        self.name = "toto"
        self.enfant = self.Child(self)  # Pass self as parent argument.

    class Child:
        def __init__(self, parent):
            self.parent = parent  # Remember parent.
            self.child_name="tata"

        def affiche(self):
            print(self.parent.name) # Display the parent's name.


parent = Parent()
parent.enfant.affiche()  # -> toto
  • Related