python-3.x - 如何在python中修改/覆盖继承的类函数?

标签 python-3.x class inheritance overriding

我有确切的函数名称 say_hello在父类和继承类中。我想指定参数name在 Kitten 类中,但允许用户在 Cat 类中指定参数。

有没有办法避免需要重复行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

关于python-3.x - 如何在python中修改/覆盖继承的类函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54371507/

相关文章:

python - 与 MySQL dB 的 SSL 连接失败

c++ - 定义子类的对象

javascript - ES6 Class 使得构造函数 "+"能够被使用

java - System 类中的 ".in"静态变量的确切类是什么?

c++ - 按值将子类对象传递给采用父类(super class)对象的函数是否是明确定义的行为?

python - conda 在激活环境之外寻找库

python - 如何阻止 wkhtmltopdf.exe 弹出?

java - 如何判断 is-a 或 instanceof 关系是否适合给定情况?

c++ - 在子类构造函数中覆盖父类变量

python - 使用 super() 和使用 self 从父类调用方法有什么区别?