带参数的Python子类化过程

标签 python object arguments multiprocessing

我正在尝试创建一个对象,但作为一个新进程。我正在关注 this guide并想出了这段代码。

import multiprocessing as mp 
import time

class My_class(mp.Process):
    def run(self):
        print self.name, "created"
        time.sleep(10)
        print self.name, "exiting"
        self.x()

    def x(self):
        print self.name, "X"

if __name__ == '__main__':
    print 'main started'
    p1=My_class()
    p2=My_class()
    p1.start()
    p2.start()  
    print 'main exited'

但在这里我无法将参数传递给对象。我搜索但没有找到。它不像一个普通的多进程,我们会做类似的事情:

p1 = multiprocessing.Process(target=My_class, args=('p1',10,))

将参数传递给新进程。 但是类实例的多处理是不同的。现在我正在通过如下艰难的方式传递它。

import multiprocessing as mp 
import time

class My_class(mp.Process):
    my_vars={'name':'', 'num':0}
    def run(self):
        self.name=My_class.my_vars['name']
        self.num=My_class.my_vars['num']
        print self.name, "created and waiting for", str(self.num), "seconds"
        time.sleep(self.num)
        print self.name, "exiting"
        self.x()

    def x(self):
        print self.name, "X"

if __name__ == '__main__':
    print 'main started'
    p1=My_class()
    p2=My_class()
    My_class.my_vars['name']='p1'
    My_class.my_vars['num']=20
    p1.start()
    My_class.my_vars['name']='p2'
    My_class.my_vars['num']=10
    p2.start()  
    print 'main exited'

哪个工作正常。但我猜它可能会因复杂的参数而失败,例如大型列表或对象或类似的东西。

还有其他方法可以传递参数吗??

最佳答案

您可以只为 My_class 实现一个 __init__ 方法,它接受您要提供的两个参数:

import multiprocessing as mp 
import time

class My_class(mp.Process):
    def __init__(self, name, num):
        super(My_class, self).__init__()
        self.name = name
        self.num = num

    def run(self):
        print self.name, "created and waiting for", str(self.num), "seconds"
        time.sleep(self.num)
        print self.name, "exiting"
        self.x()

    def x(self):
        print self.name, "X"

if __name__ == '__main__':
    print 'main started'
    p1=My_class('p1', 20)
    p2=My_class('p2', 10)
    p1.start()
    p2.start()  
    print 'main exited'

你只需要确保在你的 __init__ 方法中调用 super(My_class, self).__init__() ,这样你的类就被正确地初始化为一个 Process 子类。

关于带参数的Python子类化过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28711140/

相关文章:

python - 输出未完全显示在 Python 中

python - 如何在mongodb聚合中对嵌套字段进行分组

python - Psychopy:如何显示日语?

python - Selenium Python 在获取谷歌评论时无法向下滚动

c++ - 在 main() 之外处理 argc 和 argv

Javascript 循环对象数组

c++ - 用C++类实现数组属性

swift - 在基于 swift 的应用程序中与枚举成员交互

c++ - 可变参数列表程序行为异常 - cstdarg

javascript - 传递一个函数作为参数,它使用父函数的参数,但也有它自己的参数