gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 05:32:03 28 4
gpt4 key购买 nike

文件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() 调用或 init 方法。

最佳答案

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)

现在,当第 3 方库创建事件时,它会自动传递给 engine

关于python - 在同一 Python 模块中的对象之间共享值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19986406/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com