Accessing parent objects
D'Arcy Cain
darcy at VybeNetworks.com
Sun Mar 25 06:57:40 EDT 2018
On 03/25/2018 04:37 AM, Jugurtha Hadjar wrote:
> 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.
That was my original solution but it seems clumsy.
O2 = O1.C2(O1)
IOW passing the parent object to the child class. It just seems like
there should be some way to access the parent object in C2.
> Something like this:
>
> class C1(object):
...
> class C2(object):
> def __init__(self, parent=None):
> self.parent = parent
Perhaps your email client is collapsing leading spaces but that isn't
what I wrote. The C2 class is supposed to be a member of C1. That's
why I called it as O1.C2() instead of just C2(). I was hoping that by
doing so that the data in O1 would somehow be available without having
to explicitly pass it as an argument.
However, I would have made the parameter required. I don't see the
point of calling another method to add it in later. Of course, if I do
that there's no point in making C2 part of C1. What you wrote would be
just fine and obvious.
--
D'Arcy J.M. Cain
Vybe Networks Inc.
http://www.VybeNetworks.com/
IM:darcy at Vex.Net VoIP: sip:darcy at VybeNetworks.com
More information about the Python-list
mailing list