python - 如何访问存储在 multiprocessing.Manager 列表中的类?
问题描述
我可以访问和更改列表中类的属性,如下所示:
class TestClass:
def __init__(self):
self.value = 1
instances = [TestClass()]
instances[0].value = 42
print(instances[0].value) # 42
但是,当使用 时multiprocessing.Manager
,我的代码似乎没有任何效果:
from multiprocessing import Manager
with Manager() as manager:
instances = manager.list([TestClass()])
instances[0].value = 42
print(instances[0].value) # 1
如何使用模块正确存储带有类实例的可迭代对象multiprocessing
?
解决方案
此问题与添加值以设置包含在 Multiprocessing.Manager().list() 中的重复
正如@torek 所说,代理管理器无法将您的更改传播到底层对象,因此您必须完全替换它。
注意 对 dict 和 list 代理中的可变值或项的修改不会通过管理器传播,因为代理无法知道其值或项何时被修改。要修改此类项目,您可以将修改后的对象重新分配给容器代理:
# create a list proxy and append a mutable object (a dictionary) lproxy = manager.list() lproxy.append({}) # now mutate the dictionary d = lproxy[0] d['a'] = 1 d['b'] = 2 # at this point, the changes to d are not yet synced, but by # reassigning the dictionary, the proxy is notified of the change lproxy[0] = d
所以,这是你的解决方案:
with Manager() as manager:
instances = manager.list([TestClass()])
newInstance = TestClass()
newInstance.value = 42
instances[0] = newInstance
print(instances[0].value)
推荐阅读
- xodus - 为什么 `toIdString` 是 `Entity` 的成员?
- c - c整数除法不返回正确的商
- reactjs - Cannot read property 'isLoggedIn' of null
- android - 如何从 ionic/react 构建 APK 以安装在我的 android 设备上或在 google play 上发布?
- alexa - 在 Alexa 的单个自定义插槽中使用数字和短语
- python - 对多行 pandas 的 groupby 应用逻辑
- python - 我认为 scipy.interpolate 可能被破坏了或者我用错了?
- javascript - 在javascript游戏中使画布中的两个移动形状不重叠(碰撞)
- scala - java.net.MalformedURLException:无协议:将 arg 传递给 spark-submit 作业时为 null
- python - 如何为 .py 文件创建 requirements.txt?并非所有模块都通过 pip 安装,但仅涉及某些特定 .py 文件的模块