[英]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. 在Python中研究继承性,到目前为止,我的理解是,如果子类打算让该方法执行与该基类不同的操作,则该子类仅会覆盖该方法。
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): 因此,以HowDoI为例,我们在test_howdoi.py中看到了继承自unittest.TestCase
的HowdoiTestCase
类,它覆盖了TestCase
的setUp()
函数(仅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). 然后,test_howdoi.py继续覆盖tearDown()
,但是它被写入为仅pass
(根据基类的定义)。 And tearDown() does not get used anywhere. 而且tearDown()不会在任何地方使用。
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). setUp
和tearDown
方法用于单元测试运行程序中(顾名思义-测试前后)。
Why would a base class function be overwritten with the same behaviour as its behavior in the base class? 为什么用与基类中相同的行为覆盖基类函数?
Some of reasons may be: 某些原因可能是:
setUp
and tearDown
are optional and have empty implementations by default 开发人员未阅读文档,该文档指出setUp
和tearDown
是可选的,默认情况下具有空的实现 TLDR: By accident or due to personal preference. TLDR:偶然或由于个人喜好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.