我看到人们一直在做的事情是:
class Man(object):
def say_hi(self):
print('Hello, World.')
class ExcitingMan(Man):
def say_hi(self):
print('Wow!')
super(ExcitingMan, self).say_hi() # Calling the parent version once done with custom stuff.
我从未见过人们做的事情是:
class Man(object):
def say_hi(self):
print('Hello, World.')
class ExcitingMan(Man):
def say_hi(self):
print('Wow!')
return super(ExcitingMan, self).say_hi() # Returning the value of the call, so as to fulfill the parent class's contract.
这是因为我和所有错误的程序员在一起,还是有充分的理由?
最佳答案
我认为显式返回父类(super class)方法的返回值更为谨慎(除了在极少数情况下 child 想要抑制它)。尤其是当你不知道 super 到底在做什么的时候。同意,在 Python 中,您通常可以查找父类(super class)方法并找出它的作用,但仍然如此。
当然,编写其他版本的人可能自己编写了父类和/或知道它没有返回值。在那种情况下,他们会决定不使用明确的 return 语句。
关于python - 覆盖父类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3801484/