英文:
How to use variables of run method in other methods of a process class in python
问题
如何在Process类的其他方法中使用在'run'方法内创建的变量(复杂对象)?
我理解在run方法内创建或修改的变量的作用范围仅限于该方法本身,但是否有办法解决这个问题?
这是我的示例代码:
import multiprocessing as mp
class DummyCls:
def __init__(self):
self.name = "Hii"
class MyProcess(mp.Process):
def __init__(self):
super().__init__()
self.my_object = None
def run(self):
self.my_object = DummyCls()
self.my_object.name = "Hello"
def get_name(self):
print(self.my_object.name)
if __name__ == '__main__':
my_process = MyProcess()
my_process.start()
my_process.get_name()
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,
import multiprocessing as mp
class DummyCls:
def __init__(self):
self.name = "Hii"
class MyProcess(mp.Process):
def __init__(self):
super().__init__()
self.my_object = None
def run(self):
self.my_object = DummyCls()
self.my_object.name = "Hello"
def get_name(self):
print(self.my_object.name)
if __name__ == '__main__':
my_process = MyProcess()
my_process.start()
my_process.get_name()
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__'
中:
my_process = MyProcess()
my_process.start()
my_process.run() # 新增
my_process.get_name()
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__'
:
my_process = MyProcess()
my_process.start()
my_process.run() # new
my_process.get_name()
my_process.join()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论