【发布时间】:2013-11-27 23:31:18
【问题描述】:
文件引擎.py:
class Engine(object):
def __init__(self, variable):
self.variable = variable
class Event(object):
def process(self):
variable = '123' # this should be the value of engine.variable
Python
>>> from engine import Engine, Event
>>> engine = Engine('123')
>>> e = Event()
>>> e.process()
完成此任务的最佳方法是什么?由于 Event 类的限制(它实际上是我正在将新功能拼接到的第三方库的子类),我无法执行 e = Event(engine) 之类的操作。
深入解释:
为什么我不使用e = Event(engine)?
因为 Event 实际上是第三方库的子类。此外,process() 是一种内部方法。所以这个类实际上是这样的:
class Event(third_party_library_Event):
def __init__(*args, **kwargs):
super(Event, self).__init__(*args, **kwargs)
def _process(*args, **kwargs):
variable = engine.variable
# more of my functionality here
super(Event, self)._process(*args, **kwargs)
我的新模块还必须与已经使用 Event 类的现有代码无缝运行。所以我不能将引擎对象添加到每个 _process() 调用或 init 方法。
【问题讨论】:
-
类定义之间,还是模块内的所有对象?
-
模块内所有对象之间,已编辑标题。
-
你试过
globals()['variable']吗?但它很脏,我认为你的设计模型有问题。 -
如果有多个
Engine类型的对象,Event.process()怎么知道选择哪一个? -
看起来我们这里有一个XY problem。你不应该问如何做这个 distry 技巧。您应该询问如何处理这个库,提及哪个库以及您想要实现的目标。将此作为可能的解决方案提及,并询问它是否正确,如果不是如何解决它或有什么替代方案。试图修复我们不知道它是什么的东西是困难并且会产生很多歧义和误解。
标签: python