Composition - Link to another class in Python

In my example below in Python, the object is x 'has-an' object y. I would like to be able to reference methods x from y.
I can achieve this using @staticmethod, however, I am not recommended to do this.

Is there a way to refer to the entire object x from the 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 xymodify() print x.count >>> # it will print 7 (x.count=7) 

Thanks in advance.

+4
source share
2 answers

You need to save a reference to an object that has an instance of object Y:

 class X(object): def __init__(self): self.count = 5 self.y = Y(self) #create ay 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() 

Usage example:

 >>> x = X() >>> xymodify() >>> x.count 7 
+10
source

Is it possible for you to use class inheritance? For instance:

 class X(object): def __init__(self): self.count = 5 def add2(self): self.count += 2 class Y(X): def __init__(self): super(Y, self).__init__() def modify(self): self.add2() y = Y() # We now create an instance of Y which is a child class of 'super' class X y.modify() print(y.count) # 7 
+2
source

Source: https://habr.com/ru/post/1491590/


All Articles