TypeError:未绑定的方法__init __()在从TDDBE通过Python练习TDD示例时

时间:2013-09-17 18:25:13

标签: python unit-testing tdd

我现在正在使用由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
你能告诉我这是什么问题吗?为什么?

1 个答案:

答案 0 :(得分:1)

WasRun类设为TestCase的子类:

class WasRun(TestCase):

现在selfTestCase的(子类)的实例。

请注意,您引用的代码并不是最佳做法;我将其重写为至少使用新式类,使用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