在同一Python模块中的对象之间共享值

在同一Python模块中的对象之间共享值,python,Python,文件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 蟒蛇 >>> from engine im

文件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
蟒蛇

>>> 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)
我的新模块还必须与已经使用事件类的现有代码无缝运行。因此,我也不能将passengine对象添加到每个_process()调用或init方法中

“由于事件类的限制(它实际上是一个子类 我正在将新功能拼接到第三方库中)I 无法执行e=事件(引擎)之类的操作。“

似乎您担心Event继承了其他类,因此无法更改该类的构造函数方法

你的问题类似于。幸运的是,
super()

考虑以下示例:

>>> 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

为什么不将变量传递到
过程
函数?您说过类的构造函数不能更改,但似乎您正在定义
进程
。只要做到:

    def process(self, engine):
        variable = engine.variable
        <do stuff>
def过程(自身、发动机):
变量=引擎变量

def过程(自身,变量):
可能有帮助:

#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

?在模块内的所有对象之间,编辑标题。您是否尝试过
globals()['variable']
?但是它很脏,我认为您的设计模型中存在一个问题。如果有多个类型为
Engine
的对象,
Event.process()
如何知道选择哪一个?看起来我们这里有一个。你不应该问怎么做这个游戏。你应该询问如何处理这个库,提到哪个库以及你想要实现什么。将此作为一个可能的解决方案提及,并询问它是否正确(如果不知道如何修复它或有什么替代方案)。试图修复一些我们不知道是关于什么的东西是很困难的,并且会产生很多歧义和误解。这只有在他正在构建
事件时才有帮助。第三方库可能正在从传入的类对象构造事件ᵩ: 如果是这样的话,那么OP应该提到它。到目前为止,唯一合理的答案是…请参阅我的编辑以获得更好的解释哦,很好!这可能是最好的选择。但是,这仅适用于您必须将
事件
传递给第三方库的情况,而您尚未透露该库。
#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)