bri*_*100 3 python python-3.x python-class
我正在阅读方法重写,在其他语言中,似乎要完全重写,该方法必须具有相同的签名(参数、返回类型...等)
所以我试图检查 python 是否是这样工作的,我尝试了下一个代码
class Person():
def __init__(self, name, age):
self.name = name
self.age = age
def print_name(self, last_name):
print(self.name + " " + last_name)
class Superhero(Person):
def __init__(self, name, age, power):
super().__init__(name, age)
self.power = power
def print_name(self):
print(self.name)
human = Person("Ron", 23)
super_human = Superhero("Superman", 30, "Flying")
human.print_name("Wesley")
super_human.print_name("Kent")
Run Code Online (Sandbox Code Playgroud)
我收到一个错误,super_human.print_name("Kent")它需要一个参数,但我传递了两个参数,我知道 MRO 存在于 python 中,我在其中查看(对象>类>父类),所以我想知道是否有一个这样我就可以调用print_name()父类中存在的函数而不是当前函数,因为它们采用不同的参数。
如果您要重写基类方法,则参数应始终与您要重写的方法兼容。这是可以从里氏替换原理中得出的基本准则之一
如果您希望该函数在未提供参数的情况下以与 super 方法不同的方式运行,那么您可以执行以下操作:
class Superhero(Person):
def __init__(self, name, age, power):
super().__init__(name, age)
self.power = power
def print_name(self, last_name=None):
if last_name is None:
print(self.name)
else:
super().print_name(last_name)
Run Code Online (Sandbox Code Playgroud)
这保留了 super 方法定义的契约,现在允许类Superhero以不同的方式处理值。如果你总是想扔掉姓氏,那么就这样做:
class Superhero(Person):
def __init__(self, name, age, power):
super().__init__(name, age)
self.power = power
def print_name(self, last_name=None):
print(self.name)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1451 次 |
| 最近记录: |