我想从两个基类(ExampleTestRun和Thread)动态创建一个类。主要目的是在线程中启动ExampleTestRun方法“run”(通过调用Thread类的方法“start”)。我从来没有在Python中使用super()。也许这将是一个答案?如何在Python中动态类创建后调用父类的__init__方法?
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
为什么要定义一个空的'__init__'方法? – BrenBarn 2014-11-03 08:00:57
BrenBarn:在BaseTest中? – kepurlaukis 2014-11-03 08:16:03
是的。如果你只是删除它,它会正常工作。 – BrenBarn 2014-11-03 18:42:42