如果我有一个python类
from multiprocessing import Process
class A(Process):
def run(self):
self.var = "asdf"
def pprint(self):
print(self.var)
if __name__ == "__main__":
foo = A()
foo.start()
foo.pprint()
bar = A()
bar.pprint()
我收到了追溯错误
Traceback (most recent call last):
File "simple.py", line 13, in <module>
foo.pprint()
File "simple.py", line 8, in pprint
print(self.var)
AttributeError: 'A' object has no attribute 'var'
我可以访问在run函数中定义的实例变量,并在类的范围内定义其他函数吗?
答案 0 :(得分:0)
from multiprocessing import Process
class A(Process):
def __init__(self, value):
self.var = value
def run(self):
self.var = "asdf"
def pprint(self):
print(self.var)
foo = A("asdf")
foo.start()
foo.pprint()
bar = A("qwerty")
bar.pprint()
答案 1 :(得分:0)
run()
函数在另一个进程中执行,变量仅在那里创建,而pprint()
在当前进程中执行。你可以,例如使用Manager
获取dict
来存储所有进程通用的数据或使用管道或队列交换数据(阅读相关文档)。