Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将代码追加到继承的类方法_Python_Class_Append - Fatal编程技术网

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

调用父方法,然后执行要添加的操作。