python-3.x - 如何在python中修改/覆盖继承的类函数?
问题描述
我say_hello
在父类和继承类中都有确切的函数名称。我想name
在 Kitten 类中指定参数,但允许用户在 Cat 类中指定参数。
有没有办法避免需要在 Kitten 类return ('Hello '+name)
的函数中重复该行?say_hello
目前:
class Cat:
def __init__(self):
pass
def say_hello(name):
return ('Hello '+name)
class Kitten(Cat):
def __init__(self):
super().__init__()
def say_hello(name='Thomas'):
return ('Hello '+name)
x = Cat
print (x.say_hello("Sally"))
y = Kitten
print (y.say_hello())
理想情况下:
class Cat:
def __init__(self):
pass
def say_hello(name):
return ('Hello '+name)
class Kitten(Cat):
def __init__(self):
super().__init__()
def say_hello():
return super().say_hello(name='Thomas') # Something like this, so this portion of the code doesn't need to repeat completely
解决方案
该say_hello
方法应包含self
作为第一个参数,以便它可以使用该super()
函数访问父say_hello
方法。您还应该通过用括号调用它来实例化一个类:
class Cat:
def say_hello(self, name):
return 'Hello ' + name
class Kitten(Cat):
def say_hello(self, name='Thomas'):
return super().say_hello(name)
x = Cat()
print(x.say_hello("Sally"))
y = Kitten()
print(y.say_hello())
这输出:
Hello Sally
Hello Thomas
推荐阅读
- jquery - bootstrap-multiselect 如果组没有选项,则默认选择 optgroup
- r - 通过停止函数的特定返回进行重构
- javascript - 无法将字符串变量传递给 JS 日期对象
- python - 如何按两列分组并在新列中分配类别(数字)?
- wikidata-api - Wikidata Api - 子实例和子类的距离树
- python - 抽象类应该返回与预期实现方法相同的类型吗?
- jmeter - Jmeter 没有 GUI 模式运行 .jmx 不包括运行覆盖方法 getDefaultParameters()
- c# - 获取进程关闭原因信息
- nest - 默认 JsonNetSerializer 不使用驼峰式属性名称
- python - Postgres 是否缓存了我们的查询,我们如何绕过它?