【发布时间】:2019-06-19 15:44:54
【问题描述】:
我在父类和继承类中都有确切的函数名称say_hello。我想在 Kitten 类中指定参数name,但允许用户在 Cat 类中指定参数。
有没有办法避免在 Kitten 类的 say_hello 函数中重复 return ('Hello '+name) 行?
目前:
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
【问题讨论】:
-
我只是想这可以使用
return Cat.say_hello(name='Thomas')来完成。这是做我想做的事情的正确方法吗?
标签: python-3.x class inheritance overriding