0

私はこのようなクラスを持っています

class MainClass():
    blah blah blah

class AnotherClass():
    def __init__(self, main_class):
          self.main_class = main_class

    def required_method(self):
          blah blah blah

構成(継承ではなく)の使用方法についてはあまり知りませんが、上記のようなことをしなければならないと思います。

私の要件は次のとおりです。

次のように MainClass のインスタンスを使用して、AnotherClass() の関数を呼び出すことができるはずです。

main_class.AnotherClass.required_method()

今のところ、私はこれを行うことができます:

 main_class = MainClass()
 another = AnotherClass(main_class)
 another.required_method()

ありがとう。

4

2 に答える 2

0

コンポジションを使用する場合、主にいくつかのクラス機能を別のクラスに隠したいためです。

class ComplexClass(object):
    def __init__(self, component):
        self._component = component

    def hello(self):
        self._component.hello()

class Component(object):
    def hello(self):
        print "I am a Component" 

class AnotherComponent(object):
    def hello(self):
        print "I am a AnotherComponent" 


>>> complex = ComplexClass(Component()):
>>> complex.hello()
>>> I am a Component
>>> complex = ComplexClass(AnotherComponent()):
>>> complex.hello()
>>> I am a AnotherComponent

ここでComplexClassは を使用してComponentいますが、 のユーザーは、 でComplexClass何をするかを知る必要はありません (知っておくべきではありません) Component

もちろん、いつでもできます

complex._component.hello()

whencomplexは他のオブジェクトの単なるコンテナです (その後_component は である必要があります component)。それはOKですが、それは構成のポイントではありません

于 2013-04-26T11:57:38.110 に答える