带参数的 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屋!