如何在Python中的进程类的其他方法中使用run方法的变量

huangapple go评论99阅读模式
英文:

How to use variables of run method in other methods of a process class in python

问题

如何在Process类的其他方法中使用在'run'方法内创建的变量(复杂对象)?

我理解在run方法内创建或修改的变量的作用范围仅限于该方法本身,但是否有办法解决这个问题?

这是我的示例代码:

  1. import multiprocessing as mp
  2. class DummyCls:
  3. def __init__(self):
  4. self.name = "Hii"
  5. class MyProcess(mp.Process):
  6. def __init__(self):
  7. super().__init__()
  8. self.my_object = None
  9. def run(self):
  10. self.my_object = DummyCls()
  11. self.my_object.name = "Hello"
  12. def get_name(self):
  13. print(self.my_object.name)
  14. if __name__ == '__main__':
  15. my_process = MyProcess()
  16. my_process.start()
  17. my_process.get_name()
  18. my_process.join()

我收到以下错误:

print(self.my_object.name)
AttributeError: 'NoneType' object has no attribute 'name'

英文:

How to use a variable(Complex Object) created inside 'run' method in other methods of the Process class?

I understood the scope of variables created or modified inside run method is limited within itself, but is there any way to crack this ?

This is my sample code,

  1. import multiprocessing as mp
  2. class DummyCls:
  3. def __init__(self):
  4. self.name = "Hii"
  5. class MyProcess(mp.Process):
  6. def __init__(self):
  7. super().__init__()
  8. self.my_object = None
  9. def run(self):
  10. self.my_object = DummyCls()
  11. self.my_object.name = "Hello"
  12. def get_name(self):
  13. print(self.my_object.name)
  14. if __name__ == '__main__':
  15. my_process = MyProcess()
  16. my_process.start()
  17. my_process.get_name()
  18. my_process.join()

I'm getting error stating that,

> print(self.my_object.name)
> AttributeError: 'NoneType' object has no attribute 'name'

答案1

得分: 1

my_process.my_object 从未被实例化,因为 my_process.run() 从未被调用。

修复的方法之一是将以下内容添加到您的 if __name == '__main__' 中:

  1. my_process = MyProcess()
  2. my_process.start()
  3. my_process.run() # 新增
  4. my_process.get_name()
  5. my_process.join()
英文:

my_process.my_object is never instantiated, because my_process.run() is never called.

One way to fix it would be to add the following to your if __name == '__main__':

  1. my_process = MyProcess()
  2. my_process.start()
  3. my_process.run() # new
  4. my_process.get_name()
  5. my_process.join()

huangapple
  • 本文由 发表于 2023年3月8日 19:10:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75672241.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定