为什么子类会重写基类方法,但使其相同(而不是使用它)?

2024-10-02 02:37:58 发布

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

研究Python中的继承,到目前为止,我的理解是,如果一个子类打算让基类的方法执行与基类不同的操作,那么它只会覆盖基类的方法。你知道吗

HowDoI为例,我们在测试中看到了这一点_你好从unittest.TestCase继承的HowdoiTestCase类覆盖TestCasesetUp()函数(它只是pass):

   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'] 

到目前为止还可以。你知道吗

试验_你好然后继续覆盖tearDown(),但是它只被写入pass(根据基类的定义)。tearDown()在任何地方都不会使用。你知道吗

  • 为什么基类函数会被与基类中的行为相同的行为覆盖?你知道吗
  • 如果没有使用它的意图,为什么它会被覆盖呢?你知道吗

Tags: 方法函数selfdefsetuppassunittest基类
1条回答
网友
1楼 · 发布于 2024-10-02 02:37:58

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

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方法在unittest运行程序中使用(顾名思义-测试前后)。你知道吗

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

其中一些原因可能是:

  • IDEs生成了TestCase类存根,开发人员保留了它
  • 开发人员没有阅读文档,文档说明setUptearDown是可选的,默认情况下有空的实现
  • 一些开发人员喜欢显式地编写当前测试套件的setUp/tearDown为空

TLDR:由于意外或个人喜好。你知道吗

相关问题 更多 >

    热门问题