如何实例化具有初始值的类?

时间:2015-02-01 16:03:21

标签: python multiprocessing

我有这个脚本,我想将一个值从循环传递给My_Class:

class My_Class(multiprocessing.Process):

    def run(self):
        print 'Hello from a class'
        return

if __name__ == '__main__':
    for x in range(100):
        process = My_Class()
        process.start()

例子:来自1级的你好; 怎么能做到这个?

2 个答案:

答案 0 :(得分:-1)

您的init中似乎缺少对超类的调用。虽然我不确定这里的用例是什么,但这段代码对我有用:

import multiprocessing


class My_Class(multiprocessing.Process):
    def __init__(self, initial_value):
        super(My_Class, self).__init__()
        self.v = initial_value

    def run(self):
        print 'Hello from a class ' + str(self.v)
        return


if __name__ == '__main__':
    for x in range(100):
        process = My_Class(x)
        process.start()

答案 1 :(得分:-2)

class My_Class(multiprocessing.Process):

    def __init__(self, initial_value):
        super(My_Class, self).__init__()
        v=initial_value

    def run(self):
        print 'Hello from a class '+self.v
        return

if __name__ == '__main__':
    for x in range(100):
        process = My_Class(x)
        process.start()