如果我在当前 class 中有一个同名函数,我该如何调用父方法(如果可能)
how do i call the parent method if i have a function with the same name in the current class (if possible)
我正在阅读方法覆盖和其他语言,似乎要完全覆盖,该方法必须具有相同的签名(参数、return 类型...等)
所以我试图检查它是否与 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")
并且我在 super_human.print_name("Kent")
部分收到一个错误,它需要一个参数但我传递了两个,我知道 MRO 存在于 python 我查看的地方(对象> class > parent class), 所以我想知道是否有一种方法可以调用父 class 中存在的 print_name()
函数而不是当前函数,因为他们采用不同的参数。
如果您要重写基础 class 方法,参数应始终与您要重写的内容兼容。这是可以从 Liskov Substitution Principle
中获取的基本准则之一
如果您希望函数在未提供参数的情况下与 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)
这保留了 super 方法定义的契约,现在允许 Superhero
class 以不同方式处理值。如果你总是想丢掉姓氏,那么就这样做:
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)
我正在阅读方法覆盖和其他语言,似乎要完全覆盖,该方法必须具有相同的签名(参数、return 类型...等)
所以我试图检查它是否与 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")
并且我在 super_human.print_name("Kent")
部分收到一个错误,它需要一个参数但我传递了两个,我知道 MRO 存在于 python 我查看的地方(对象> class > parent class), 所以我想知道是否有一种方法可以调用父 class 中存在的 print_name()
函数而不是当前函数,因为他们采用不同的参数。
如果您要重写基础 class 方法,参数应始终与您要重写的内容兼容。这是可以从 Liskov Substitution Principle
中获取的基本准则之一如果您希望函数在未提供参数的情况下与 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)
这保留了 super 方法定义的契约,现在允许 Superhero
class 以不同方式处理值。如果你总是想丢掉姓氏,那么就这样做:
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)