首页 > 解决方案 > 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 方法是 Hooks,所以没有实现,我们不需要在 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 中为 setUp 和 tearDown 方法调用 super ?我看到的唯一方法是创建两个具有其他名称的方法,因此 MyThingTestClass 应该覆盖它们而不是默认方法。但我不希望这样,因为每个人都知道这些名称并想使用它们。

谢谢

标签: python

解决方案


推荐阅读