将代码附加到继承的 class 方法

Append code to inherited class method

您将如何附加到继承对象的方法?比如说:

class ABeautifulClass(GoodClass):
    def __init__(self, **kw):
        # some code that will override inherited code
    def aNewMethod(self):
        # do something

现在我已经从 GoodClass 继承了代码,如何将代码附加到继承的方法。如果我从 GoodClass 继承代码,我将如何附加到它,而不是基本上删除它并重写它。这在 Python 中可能吗?

尝试使用 super

class ABeautifulClass(GoodClass):
    def __init__(self, **kw):
        # some code that will override inherited code
    def aNewMethod(self):
        ret_val = super().aNewMethod() #The return value of the inherited method, you can remove it if the method returns None
        # do something

Learn more about super here

在 Python 中,必须通过 super 关键字显式调用 superclass 方法。所以这取决于你是否这样做,以及你在你的方法中的什么地方这样做。如果你不这样做,那么你的代码将有效地替换来自父 class 的代码;如果您在方法的开头执行此操作,您的代码将有效地附加到它。

def aNewMethod(self):
    value = super(ABeautifulClass, self).aNewMethod()
    ... your own code goes here