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: