将代码追加到继承的类方法

2024-10-02 22:23:02 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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


Tags: 对象方法代码selfthatinitdefcode
2条回答

在Python中,必须通过super关键字显式地调用超类方法。所以这取决于你是否这样做,以及在你的方法中你在哪里做。如果不这样做,那么您的代码将有效地替换父类中的代码;如果您在方法的开头这样做,那么您的代码将有效地附加到它后面。在

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

试着用超级

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

相关问题 更多 >