Kub*_*888 6 inheritance overriding class python-3.x
我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())
Run Code Online (Sandbox Code Playgroud)
理想情况下:
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
Run Code Online (Sandbox Code Playgroud)
该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())
Run Code Online (Sandbox Code Playgroud)
这输出:
Hello Sally
Hello Thomas
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5707 次 |
| 最近记录: |