[英]How can I create functions which access variables that are created in the run function of a subclassed python Process
If I have a python class 如果我有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()
I get the traceback error 我收到回溯错误
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'
Can I access instance variables that are defined within the run function, with other functions defined in the scope of the class? 我可以访问在run函数中定义的实例变量以及在类范围内定义的其他函数吗?
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()
The run()
function is executed in another process and the variable is only created there while pprint()
is executed in current process. run()
函数在另一个进程中执行,并且仅在当前进程中执行pprint()
时在pprint()
创建变量。 You can eg use a Manager
to get a dict
to store data common for all processes or exchange data using pipes or queues (read the documentation about that). 您可以如使用
Manager
得到dict
存储共同使用管道或队列(阅读有关的文档)的所有进程或交换数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.