我现在正在使用由Kent Beck编写的测试驱动开发实例通过python练习TDD。在示例中,我编写了与TDDBE中的示例相同的代码。
class TestCase:
def __init__(self, name):
self.name = name
def run(self):
exec "self." + self.name + "()"
class WasRun:
def __init__(self, name):
self.wasRun = None
TestCase.__init__(self, name)
def testMethod(self):
self.wasRun = 1
test = WasRun("testMethod")
print test.wasRun
test.run()
print test.wasRun
但是当我运行此代码时,我发现了以下错误消息。
Traceback (most recent call last):
File "/Users/sanghee/PycharmProjects/test/test.py", line 17, in <module>
test = WasRun("testMethod")
File "/Users/sanghee/PycharmProjects/test/test.py", line 11, in __init__
TestCase.__init__(self, name)
TypeError: unbound method __init__() must be called with TestCase instance as first argument (got WasRun instance instead)
Process finished with exit code 1
你能告诉我这是什么问题吗?为什么?
答案 0 :(得分:1)
将WasRun
类设为TestCase
的子类:
class WasRun(TestCase):
现在self
是TestCase
的(子类)的实例。
请注意,您引用的代码并不是最佳做法;我将其重写为至少使用新式类,使用super()
来调用超类初始化程序,并避免使用exec
语句:
class TestCase(object):
def __init__(self, name):
self.name = name
def run(self):
getattr(self, self.name)()
class WasRun(TestCase):
def __init__(self, name):
self.wasRun = False
super(WasRun, self).__init__(name)
def testMethod(self):
self.wasRun = True