从组件对象Python调用容器对象的方法

时间:2016-01-28 15:54:58

标签: python python-2.7 oop

我在Python中有两个类:

class Component(object):
    def __init__(self):
        self.flag = False

    def compnent_method(self):
        if self.flag:
            # Call a method, called_from_component, from the container

class Container(object):
    def __init__(self):
        self.component = Component()

    def container_method(self):
        self.component.component_method()

    def called_from_component(self):
        # Do some stuff. This is the method I want self.component to call

从容器中调用container_method将从组件对象中调用component_method。根据{{​​1}}的值,我想从组件对象中调用驻留在容器中的方法component.flag

如何在Python 2.7中执行此操作?

1 个答案:

答案 0 :(得分:0)

我认为您只需要将容器实例传递到component_method

class Component(object):
    def __init__(self):
        self.flag = False

    def component_method(self, container):
        if self.flag:
            # Call a method, called_from_component, from the container
            container.called_from_component()

class Container(object):
    def __init__(self):
        self.component = Component()

    def container_method(self):
        self.component.component_method(self) ## <--- Here

    def called_from_component(self):
        # Do some stuff. This is the method I want self.component to call

另一种方法是将Container实例传递给Component的构造函数:

class Component(object):
    def __init__(self, container):
        self.flag = True
        self.container = container

    def component_method(self):
        if self.flag:
            # Call a method, called_from_component, from the container
            self.container.called_from_component()

class Container(object):
    def __init__(self):
        self.component = Component(self)  ## <---- Here

    def container_method(self):
        self.component.component_method()

    def called_from_component(self):
        # Do some stuff. This is the method I want self.component to call
        print 'Called from component'