Reputation: 4998
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
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
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
Upvotes: 4