繁体   English   中英

我如何创建函数来访问在子类python进程的run函数中创建的变量

[英]How can I create functions which access variables that are created in the run function of a subclassed python Process

如果我有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函数中定义的实例变量以及在类范围内定义的其他函数吗?

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()

run()函数在另一个进程中执行,并且仅在当前进程中执行pprint()时在pprint()创建变量。 您可以如使用Manager得到dict存储共同使用管道或队列(阅读有关的文档)的所有进程或交换数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM