6

以下の Python の例では、オブジェクト x はオブジェクト y を 'has-an' としています。y から x のメソッドを呼び出せるようにしたいと考えています。
@staticmethod を使用してそれを達成することはできますが、それを行うことはお勧めしません。

オブジェクトyからオブジェクト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)

前もって感謝します。

4

2 に答える 2

12

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
于 2013-07-16T08:13:26.350 に答える
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
于 2013-07-16T08:26:12.150 に答える