为什么 subclass 会覆盖基础 class 方法但使其相同(而不使用它)?

Why a subclass would override a base class method but make it identical (and not use it)?

研究 Python 中的继承,目前我的理解是子class 仅覆盖基类 class 的方法,如果它打算让方法做某事与基础 class.

不同

所以以HowDoI为例,我们看到在test_howdoi.py中继承自unittest.TestCaseHowdoiTestCaseclass覆盖了TestCasesetUp() 函数(只有 passes):

   def setUp(self):                                          
       self.queries = ['format date bash',                   
                       'print stack trace python',           
                       'convert mp4 to animated gif',        
                       'create tar archive']                 
       self.pt_queries = ['abrir arquivo em python',         
                          'enviar email em django',          
                          'hello world em c']                
       self.bad_queries = ['moe',                            
                           'mel'] 

到目前为止还可以。

test_howdoi.py 然后继续覆盖 tearDown(),但它只写入 pass(根据基础 class 的定义)。而且 tearDown() 不会在任何地方使用。

您所描述的结构可能会简化为以下代码:

class A(object):
    def f(self):
        pass

class B(A):
    # this declaration is redundant since exact same behaviour is already inherited.
    def f(self):  
        pass

并尝试回答您的问题:

Why would it be overwritten at all if there is no intention to use it?

setUptearDown 方法用于单元测试运行程序(顾名思义 - 测试前后)。

Why would a base class function be overwritten with the same behaviour as its behavior in the base class?

部分原因可能是:

  • IDE 生成了 TestCase class 存根,开发人员只是保留了它
  • 开发人员没有阅读文档,其中指出 setUptearDown 是可选的并且默认情况下具有空实现
  • 一些开发人员喜欢明确地写 setUp / tearDown 对于当前测试套件是空的

TLDR:偶然或由于个人喜好。