Accessing parent objects

Chris Angelico rosuav at gmail.com
Sun Mar 25 06:17:59 EDT 2018


On Sun, Mar 25, 2018 at 8:37 PM, Jugurtha Hadjar
<jugurtha.hadjar at gmail.com> 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.

Congrats, this ranks on my list of "creative people who sound like
psycho murderers". Digital artists and cooks tend to rank fairly
highly on that list.

> class C1(object):
>     def __init__(self):
>         self.child = None
> class C2(object):
>     def __init__(self, parent=None):
>         self.parent = parent

The trouble with this is that there's fully-constructed objects with
no parent-child relationships. Why should you have a two-step
construction process? It makes a LOT more sense to simply require a
parent on construction, rather than feeding one to the other in a
post-construction assignment. And if you remove the default here, your
suggestion isn't materially different from what's already been posted.

ChrisA



More information about the Python-list mailing list