如何在Python中创建动态类后调用父类的__init__方法?

时间:2014-11-03 07:54:29

标签: python multithreading super

我想从两个Base类(ExampleTestRun和Thread)动态创建一个类。这样做的主要目的是启动ExampleTestRun方法"运行"在一个线程中(通过调用Thread类方法" start")。我从未在Python中使用过super()。也许这会是一个答案?

from threading import Thread

class BaseTest(object):
    def __init__(self):
        pass

class ExampleTestRun(BaseTest):

    def run(self):

        try:
            a = int('A')
        except Exception as ex:
            print ex



if __name__ == "__main__":

    test_class = type('TestClass', (ExampleTestRun, Thread), {})
    test = test_class()
    test.start()

我收到了错误:

Traceback (most recent call last):
  File "D:/Dropbox/Workspaces/PyCharmWorkspace/ElgsisTests/src/mcltests/mcltransparent/run.py", line 30, in <module>
    test.start()
  File "C:\Python27\lib\threading.py", line 737, in start
    raise RuntimeError("thread.__init__() not called")
RuntimeError: thread.__init__() not called

1 个答案:

答案 0 :(得分:1)

它会抛出该错误,因为您正在覆盖新创建的类的__init__。完全用pass替换重新定义将解决它:

class BaseTest(object):
    pass

当然,如果你想扩展原始构造函数,你将不得不诉诸super。所以完整的代码将如下所示:

from threading import Thread

class BaseTest(object):
    def __init__(self):
        super(BaseTest, self).__init__()

class ExampleTestRun(BaseTest):

    def run(self):

        try:
            a = int('A')
        except Exception as ex:
            print ex

if __name__ == "__main__":

    test_class = type('TestClass', (ExampleTestRun, Thread), {})
    test = test_class()
    test.start()