lapisdecor
lapisdecor

Reputation: 263

Acessing a property from a parent object

In python, I'm creating an object inside a class:

class A:
     def __init__(self):
         self.one = 1
         self.two = B()

Now I define class B, and I want to access self.one from inside B()

class B()
    def __init__(self):
        self.three = "hello"
        # here I want to change self.one from class A to self.one + 1
        # how to do it without doing self.two = B(self.one) on class A
        # definition?

something = A()

is there a way to reference the parent object property, or do we have to pass the value when creating the object ?

Upvotes: 0

Views: 42

Answers (1)

lejlot
lejlot

Reputation: 66835

A is not a parent object, parent object is the object from which you inherit. B has no knowledge about A, you have to modify your classes structure, for example by passing reference to parent in B's constructor (which you say you do not want to do, althouth it is not entirely clear what do you mean by "without doing self.two = B(self.one)", as this would pass copy of self.one, not a reference, but this is the way to do it)

class A:
     def __init__(self):
         self.one = 1
         self.two = B(self)

class B()
    def __init__(self, parent):
        self.three = "hello"
        self.parent = parent

        print self.parent.one # or do whatever you want with it

If you really have to do this, you can use introspection, but this is ugly, hacky, bad way of achieving the result

import inspect        

class A():
    def __init__(self):
        self.one = 1
        self.two = B()

class B():
    def __init__(self):
        self.three = "hello"
        self.parent = inspect.currentframe().f_back.f_locals['self']

        print self.parent.one

Upvotes: 2

Related Questions