带参数的Python子类化过程 [英] Python subclassing process with parameter
问题描述
我正在尝试创建一个对象,但这是一个新过程.我正在遵循本指南,并想出了这段代码.>
I'm trying to create an object but as a new process. I'm following this guide and came up with this code.
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'
但是在这里,我无法将参数传递给该对象.我搜索了但没有找到.这不像正常的多进程,我们会做类似的事情:
But here I'm unable to pass arguments to the object. I searched but found none. It's not like a normal multiprocess where we'd be doing something like:
p1 = multiprocessing.Process(target=My_class, args=('p1',10,))
将参数传递给新进程. 但是类实例的多重处理是不同的.现在,我正在像下面这样艰难地通过它.
to pass the arguments to the new process. But the multiprocessing for a class instance is different. For now I'm passing it the hard way like below.
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'
哪个工作正常.但是我想对于像大型列表或对象之类的复杂参数,它可能会失败.
Which is working fine. But I guess it may fail for complex arguments like a large list or object or something like that.
还有其他方法可以传递参数吗?
Is there any other method to pass the arguments??
推荐答案
您可以为My_class
实现一个__init__
方法,该方法采用您要提供的两个参数:
You can just implement an __init__
method for My_class
, which takes the two parameters you want to provide:
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
子类.
You just need to be sure to call super(My_class, self).__init__()
in your __init__
method, so that your class is properly initialized as a Process
subclass.
这篇关于带参数的Python子类化过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!