Python类方法钩子和派生

2024-05-13 17:45:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

import unittest


class MyBaseThingTestClass(unittest.TestCase):
    """
    Abstract
    """

    def setUp(self):
        # Is a hook in unittest.TestCase
        self.x = 1

    def tearDown(self):
        # Is a hook in unittest.TestCase
        self.x = 0


class MyThingTestClass(MyBaseThingTestClass):
    """
    Real Test
    """

    def setUp(self):
        print('I do what I want')
        super(MyThingTestClass, self).setUp()

    def tearDown(self):
        print('Im done')
        super(MyThingTestClass, self).tearDown()

    def test_x(self):
        assert self.x == 1

if __name__ == '__main__':
    unittest.main()

unittest.TestCase的setUp和tearDown方法是钩子,因此没有实现,我们不需要在MyBaseThingTestClass中调用super:

def setUp(self):
    "Hook method for setting up the test fixture before exercising it."
    pass

def tearDown(self):
    "Hook method for deconstructing the test fixture after testing it."
    pass

我的问题是:有没有可能像我一样开发两级派生,而不需要在MyThingTestClass中调用super来获取setUp和tearDown方法? 我看到的唯一方法是创建两个具有其他名称的方法,因此MyThingTestClass应该覆盖它们,而不是默认的方法。但我不想这样,因为每个人都知道这些名字,而且都想使用它们

谢谢


Tags: 方法intestselfisdefsetupunittest