Accessing parent objects

Chris Angelico rosuav at gmail.com
Sat Mar 24 16:01:02 EDT 2018


On Sun, Mar 25, 2018 at 5:14 AM, D'Arcy Cain <darcy at vybenetworks.com> wrote:
> I'm not even sure how to describe what I am trying to do which perhaps
> indicates that what I am trying to do is the wrong solution to my
> problem in the first place but let me give it a shot.  Look at the
> following code.
>
> class C1(dict):
>   class C2(object):
>     def f(self):
>       return X['field']
>
> O1 = C1()
> O1['field'] = 1
> O2 = O1.C2()
> print(O2.f())
>
> I am trying to figure out what "X" should be.  I know how to access the
> parent class but in this case I am trying to access the parent object.
> I tried various forms of super() but that didn't seem to work.
>

What you'd need here is for O1.C2 to be an instance method, instead of
simply a nested class. That way, it can retain a reference to O1.
Something like:

class C1(dict):
    class _C2(object):
        def __init__(self, parent):
            self.parent = parent
        def f(self):
            return self.parent["field"]
    def C2(self):
        return self._C2(self)

It may also be possible to do this through __new__, but I haven't
confirmed it. Might need some careful shenanigans if you want to have
O1.C2 actually be the class.

ChrisA



More information about the Python-list mailing list