Accessing parent objects
Jugurtha Hadjar
jugurtha.hadjar at gmail.com
Sun Mar 25 06:10:55 EDT 2018
There was a typo in my original reply:
<-------------------------------------------------------------------->
class C1(object):
def __init__(self):
self.child = None
def foo(self):
print("I am {self.__class__.__name__} foo".format(self=self))
def adopt(self, child=None):
self.child = child
s = ("I am {self.__class__.__name__} and I adopted "
"{self.child.__class__.__name__}".format(self=self))
print(s)
class C2(object):
def __init__(self, parent=None):
self.parent = parent
def foo(self):
print("I am {self.__class__.__name__} foo".format(self=self))
self.parent.foo()
def adoptme(self, parent=None):
s = "I am {self.__class__.__name__} looking for adoption"
print(s.format(self=self))
parent = parent or self.parent
if parent is None:
print("No parent yet")
else:
self.parent = parent
parent.adopt(self)
c2 = C2()
c2.adoptme() # No parent yet
c1 = C1()
c2.adoptme(c1) # I am C2 looking for adoption
# I am C1 and I adopted C2
c2.foo() # I am C2 foo
# I am C1 foo
c1.adopt(c2) # I am C1 and I adopted C2
<------------------------------------------------------------------------>
--
~ Jugurtha Hadjar,
More information about the Python-list
mailing list