我有三个模块
(1)mem.py
memory = {}
class test(object):
def __init__(self):
global memory
self.internal = memory
def set(self,key,value):
self.internal[key]=value
def printmem(self):
print self.internal
(2)computer1.py
from mem import test
comp1 = test()
comp1.set(1,2)
comp1.printmem()
(3)computer2.py
from mem import test
comp2 = test()
comp2.set(3,4)
comp2.printmem()
现在,在交互式 shell 中,我运行computer1.py,然后运行computer2.py。结果不是我想要的。当我运行computer2.py时,我希望comp2.printmem()打印{1:2,3:4},因为内存是全局的,它应该将{1:2}从comp1携带到comp2,但它只打印{3: 4}。我怎样才能解决这个问题 ?
最佳答案
不,你错了@LuckyStarr。每个进程都有自己的内存片。当您运行 python computer1.py
时,Python 解释器会加载 computer1.py
,它会导入 mem.py
。此调用的 Python 解释器使用一定量的内存,mem.py
全局变量驻留在其中。一旦 computer1.py
执行完毕,进程就会干净地退出,释放所有使用的内存。
现在,当您运行 computer2.py
时,同样的事情会再次发生,即 computer2.py
被加载到一个新的 Python 进程中,该进程会获取新的内存,从而加载 mem.py
,然后从所有模块创建的对象在该 Python 进程的生命周期内都存在于内存中。
mem.py
没有单独的内存共享。它是具有特定共享内存的Python进程,Python进程负责加载所有模块,包括mem.py和其他模块,如computer1.py。并且在该Python进程的跨度中加载创建的对象仅保留在内存中,直到该进程运行为止。
无论如何,您都将 computer1.py
和 computer2.py
作为单独的 Python 进程运行 - 在决定这样做之前,它们无法访问彼此的内存使用一些其他技术。
关于python使用oop在两个模块之间共享内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24479281/