简体   繁体   English

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

[英]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.

相关问题 如何在其他函数可以在python中访问的函数中创建变量? - How do I create a variable in a function that other functions can access in python? Python - 如何将单独的模块(不运行)作为单独的进程运行? - Python - how can I run separate module (not function) as a separate process? 在python中定义一个主要函数,该函数可以在python中运行其他函数 - Define a main function in python which can run other functions in python 如何访问 Python 鼻子测试设置函数中设置的变量 - How can I access variables set in the Python nosetests setup function 如何从用Python编写的FORTRAN访问函数? - How can I access a function from FORTRAN which is writen in Python? PYTHON3 - 我可以在函数之外存储在函数中创建的变量吗 - PYTHON3 -Can I store variables created in a function outside of the function 如何访问嵌套函数中更多全局函数中的变量? (蟒蛇) - How to access variables in more global functions within a nested function? (Python) 如果我在一个 function 中创建了小部件,我如何使用 PythonE460F8BEA5A9F5118 在另一个 function 中访问它们 - If I created widgets in one function, how can I access them in another function using Python Tkinter? Tkinter-我如何在新窗口中创建按钮,该窗口是由调用函数创建的? Python 3 - Tkinter - How would I create buttons in a new window, which has been created by a function being called? Python 3 如何在Python和RobotFramework之间传递在Python函数内部创建的变量 - How to pass variables between Python and RobotFramework which are created inside Python functions
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM