我在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中执行此操作?
答案 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'