Zizouz212
Zizouz212

Reputation: 4998

Append code to inherited class method

How would you append to the method of an inherited object? Say, for example:

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

Now I have inherited code from GoodClass, how would I append code to an inherited method. If I inherited code from GoodClass, how would I append to it, instead of basically removing it and rewriting it. Is this possible in Python?

Upvotes: 3

Views: 2406

Answers (2)

Daniel Roseman
Daniel Roseman

Reputation: 599550

In Python, invoking the superclass method must be done explicitly, via the super keyword. So it's up to you whether you do that or not, and where in your method you do it. If you don't, then your code will effectively replace the code from the parent class; if you do it at the start of the method, your code effectively appends to it.

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

Upvotes: 2

no_name
no_name

Reputation: 742

Try using 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

Upvotes: 4

Related Questions