Clock Slave
Clock Slave

Reputation: 7957

Python - inherit a method from a class but with a different name

I have to define a class (call it ABC) that inherits from another class (call it SuperABC). The class I am inheriting from (SuperABC) has a method (lets call it func) that I need to use. But the problem is that I have to define a method with same name (i.e func) in class ABC which calls the func method of the SuperABC class and does additional things. I realized I could solve this issue if I can inherit the func method from SuperABC but with a different alias. Is it possible to do so?

Currently I have just copied the func method from SuperABC class, added it to the ABC class and changed its name to _func. Is there any other way to do this?

Lastly, I looked into the usage of super. But from what I have read, it looks like super can resolve the current question if I am inheriting that method only from one class. What if I was inheriting from SuperABC and BatABC and wanted to use of both of theirs func method in the func method of the ABC class by changing names or any other method? Is it possible to do so?

Upvotes: 0

Views: 609

Answers (3)

jkm
jkm

Reputation: 46

If you need to do it this particular way:

subclass_function_name = super().parentfunctionname

If you're using Python 2, you need to add the args in super(). Note this is NOT a call to the parentfunctionname but a reference to the function object.

Upvotes: 0

Ofer Sadan
Ofer Sadan

Reputation: 11922

You probably mean something like this:

class ABC(SuperABC):
    def _func(*args, **kwargs):
        return SuperABC.func(*args, **kwargs)

And if you want to get rid of the actual inheritance of the original func add:

    def func(*args, **kwargs):
        return

Another way to do that 2nd step would be to change the func during the __init__ stage, but then you might overwrite something else in there if it's not done carefully.

If you want to inherit 2 func from 2 different classes (and func is the same name in both), you would have to define an intermediary class that changes the name of one of them first

Upvotes: 2

n. m. could be an AI
n. m. could be an AI

Reputation: 119847

Just forward the call.

 def _func(*args, **kwargs):
     return func(*args, **kwargs)

Upvotes: 0

Related Questions