python-组合(不是继承)-main_instance.anotherClass.funct?怎么用?
我有一节这样的课python-组合(不是继承)-main_instance.anotherClass.funct?怎么用?,python,Python,我有一节这样的课 class MainClass(): blah blah blah class AnotherClass(): def __init__(self, main_class): self.main_class = main_class def required_method(self): blah blah blah 我不太了解如何使用堆肥(而不是继承),但我认为我必须做如上所述的事情 我的要求是: 我应该能够
class MainClass():
blah blah blah
class AnotherClass():
def __init__(self, main_class):
self.main_class = main_class
def required_method(self):
blah blah blah
我不太了解如何使用堆肥(而不是继承),但我认为我必须做如上所述的事情
我的要求是:
我应该能够使用main类的实例调用另一个类()的函数,如下所示:
main_class.AnotherClass.required_method()
到目前为止,我能够做到这一点:
main_class = MainClass()
another = AnotherClass(main_class)
another.required_method()
谢谢。如果您使用composition,主要是因为您想将某些类的功能隐藏到另一个类中:
class MainClass():
def __init__(self, another_class):
self.another_class = another_class
class AnotherClass():
def required_method(self):
blah blah blah
another = AnotherClass()
main_class = MainClass(another_class)
main_class.another_class.required_method()
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
使用组件
,但是ComplexClass
的用户不需要知道(也不应该知道)它对组件的作用
当然,你总是可以
complex._component.hello()
当复合体
只是其他对象的容器时(然后\u组件
组件
)。这是可以的,但这并不是问题的关键,请不要将该类实例作为参数传递,然后重试。我应该能够调用complexclass_instance.Component.hello()