组合 - 引用Python中的另一个类

one*_*ace 5 python

在我下面的Python例子中,对象x'有一个'对象y.我希望能够从y调用x的方法.
我能够使用@staticmethod实现它,但是我不鼓励这样做.

有没有办法从Object y引用整个Object x?

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)
Run Code Online (Sandbox Code Playgroud)

提前致谢.

Hen*_*nyH 10

您需要存储对具有Y对象实例的对象的引用:

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()
Run Code Online (Sandbox Code Playgroud)

用法示例:

>>> x = X()
>>> x.y.modify()
>>> x.count
7
Run Code Online (Sandbox Code Playgroud)