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

时间:2013-07-16 08:07:45

标签: 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)

提前致谢。

2 个答案:

答案 0 :(得分: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()

使用示例:

>>> x = X()
>>> x.y.modify()
>>> x.count
7

答案 1 :(得分:2)

也许您可以使用类继承?例如:

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