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

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

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

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:

确定