Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Composition - Reference to another class in Python

Tags:

python

In my example below in Python, object x 'has-an' object y. I'd like to be able to invoke methods of x from y.
I'm able to achieve it using @staticmethod, however I'm discouraged to do that.

Is there any way(s) to reference the whole Object x from Object y?

class X(object):
    def __init__(self):
        self.count = 5
        self.y = Y() #instance of Y created.

    def add2(self):
        self.count += 2

class Y(object):
    def modify(self):
        #from here, I wanna called add2 method of object(x)


x = X()
print x.count
>>> 5

x.y.modify()
print x.count
>>> # it will print 7 (x.count=7)

Thanks in advance.

like image 834
oneace Avatar asked Jul 16 '13 08:07

oneace


1 Answers

You need to store a reference to the object which has the instance of a Y object:

class X(object):
    def __init__(self):
        self.count = 5
        self.y = Y(self) #create a y passing in the current instance of x
    def add2(self):
        self.count += 2

class Y(object):
    def __init__(self,parent):
        self.parent = parent #set the parent attribute to a reference to the X which has it
    def modify(self):
        self.parent.add2()

Example usage:

>>> x = X()
>>> x.y.modify()
>>> x.count
7
like image 151
HennyH Avatar answered Nov 12 '22 04:11

HennyH