文件engine.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()調用或者方法或者方法中。
在類定義或模塊內的所有對象之間? –
在模塊內的所有對象之間編輯標題。 – nathancahill
你有沒有嘗試過'globals()['variable']'?但它很髒,我認爲你的設計模型存在一個問題。 –