On 03/24/2018 07:14 PM, D'Arcy Cain wrote:
class C1(dict):
class C2(object):
def f(self):
return X['field']
O1 = C1()
O1['field'] = 1
O2 = O1.C2()
print(O2.f())
I prefer to *feed* the child to the parent or vice versa. Simplifies
things like testing.
Something like this:
<---------------------------------------------------------------------->
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):
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 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,
--
https://mail.python.org/mailman/listinfo/python-list