Python 将代码追加到继承的类方法
如何附加到继承对象的方法?比如说:Python 将代码追加到继承的类方法,python,class,append,Python,Class,Append,如何附加到继承对象的方法?比如说: class ABeautifulClass(GoodClass): def __init__(self, **kw): # some code that will override inherited code def aNewMethod(self): # do something 现在我已经从GoodClass继承了代码,如何将代码附加到继承的方法中。如果我从GoodClass继承了代码,我将如何附加到它,
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
在Python中,必须通过
super
关键字显式地调用超类方法。所以这取决于你是否这样做,以及在你的方法中你在哪里这样做。如果您不这样做,那么您的代码将有效地替换父类中的代码;如果在方法开始时执行此操作,则代码将有效地附加到该方法
def aNewMethod(self):
value = super(ABeautifulClass, self).aNewMethod()
... your own code goes here
调用父方法,然后执行要添加的操作。