2013-11-14 16 views
1

文件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()調用或者方法或者方法中。

+0

在類定義或模塊內的所有對象之間? –

+0

在模塊內的所有對象之間編輯標題。 – nathancahill

+0

你有沒有嘗試過'globals()['variable']'?但它很髒,我認爲你的設計模型存在一個問題。 –

回答

1

functools.partial可能幫助:

#UNTESTED 
class Engine(object): 
    def __init__(self, variable): 
     self.variable = variable 

class Event(object): 
    def __init__(self, engine): 
     super().__init__() 
     self.engine = engine 
    def process(self): 
     print self.engine.variable 


engine = Engine('123') 
Event = functools.partial(Event, engine) 

ThirdPartyApiThatNeedsAnEventClass(Event) 

現在,當第三方庫創建一個事件,它會自動通過engine

+0

哦,太好了!這可能是最好的選擇。 – nathancahill

+0

但是,這僅適用於必須將'Event'傳遞給第三方庫的情況,該**庫仍未顯示**。 –

1

「因爲隨着事件階級侷限性的(實際上它是我新的拼接功能集成到第三方庫的一個子類 )我 不能做一些像E =事件(發動機)。 「

看來您擔心Event正在繼承其他一些類,因此您無法更改此類的構造函數方法。

您的問題與this other one類似。幸運的是,super().__init__()方法可以幫你。

請看下面的例子:

>>> class C(object): 
    def __init__(self): 
     self.b = 1 


>>> class D(C): 
    def __init__(self): 
     super().__init__() 
     self.a = 1 

>>> d = D() 
>>> d.a 
1 
>>> d.b # This works because of the call to super's init 
1 
+1

這隻有在他構建「事件」時纔有用。這有可能是第三方的lib是從在 –

+0

通過@Robᵩ類對象構造事件:如果是這樣的話,則應該OP提到它。 –

+1

到目前爲止,唯一明智的答案... –

0

爲什麼不能傳遞變量到process功能?你說過這個班的構造函數不能改變,但是好像你在定義process。只是使它:

def process(self, engine): 
     variable = engine.variable 
     <do stuff> 

def process(self, variable): 
     <do stuff> 
+0

見我的編輯爲了更好地解釋 – nathancahill