簡體   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