简体   繁体   中英

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

Studying inheritance in Python, and my understanding so far is that a subclass only overwrites a method of the base class if it is intends for the method to do something different that of the base class.

So using HowDoI as an example, we see that in test_howdoi.py the HowdoiTestCase class, which inherits from unittest.TestCase , overwrites TestCase 's setUp() function (which just pass es):

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

OK so far.

test_howdoi.py then goes on though to overwrite tearDown() , yet it is written to just pass (as per the base class's definition). And tearDown() does not get used anywhere.

  • Why would a base class function be overwritten with the same behaviour as its behavior in the base class?
  • Why would it be overwritten at all if there is no intention to use it?

Structure you're describing may be reduced to following code:

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

And trying to answer your question:

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

setUp and tearDown methods ARE used in unittest runners (as name suggests - before and after test).

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

Some of reasons may be:

  • IDEs generated TestCase class stub, developer just kept it
  • Developer didn't read docs, which states that setUp and tearDown are optional and have empty implementations by default
  • Some developers like to explicitly write that setUp / tearDown is empty for current test suite

TLDR: By accident or due to personal preference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM