Accessing parent objects

Peter Otten __peter__ at web.de
Sat Mar 24 14:53:03 EDT 2018


D'Arcy Cain 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.

You can make an arbitrary number of C1 instances and an arbitrary number of 
C2 instances; there cannot be an implicit connection between any pair.

You have to be explicit:

class C1(dict):
    def C2(self):
        return C2(self)

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

O1 = C1()
O1['field'] = 1
O2 = O1.C2()
print(O2.f())





More information about the Python-list mailing list