When using classes like this:
class Parent:
def __init__(self):
self.child = Child()
class Child:
def __init__(self):
print(self.parent) # error, I don't have any way to know my parent!
p = Parent()
of course, it returns an error because the Child
instance has no attribute parent
, this is normal.
One solution is simply to define the classes like this:
class Parent:
def __init__(self):
self.child = Child(self)
class Child:
def __init__(self, parent):
self.parent = parent
print(self.parent) # now it's ok!
But in my code, I have many classes, and it is somehow annoying to have to pass self
as parameter, all the time, when instantiating child objects:
self.child = Child(self) # pass self so that this Child instance will know its parent
and I would prefer to keep simply:
self.child = Child() # can this Child instance know its parent without passing self?
Is there a way for Python to automatically infer that an object is in fact an attribute of a parent object, without having to pass self
explicitely? If so, how to get the parent?
Example: in GUI programming when creating a Button instance, which is a member of a Panel, which is itself a member of a Window, etc. it seems we have to pass self
to children constructors all the time.
Note: I'd like to avoid using inspect
because the solutions with it seem to be poorer than just passing self
.