Skip to content
Advertisement

Inherit multiple methods with same name from multiple classes

I have two parent classes that share method names. I’d like to subclass them and reassign their methods under different names to the subclass. This is made complicated because these methods use other methods with shared names as well. Contrived but minimal example:

JavaScript

In the example above, foo.print1() prints 1 as expected, but foo.print2() prints 1 instead of 2. I would like to structure Foo such that it calls Foo2’s print and get methods and thus prints 2.

I understand this is because the name “self” actually points to Foo(), and so the methods “print” and “get” are pointing to Foo1’s methods due to Foo1 being first in the MRO.

For my use case, it doesn’t even make sense for Foo() to have “print” and “get” methods, only “print1” and “print2”. This makes me suspect that I’m going about it all wrong. Is there a better way to construct a subclass that correctly inherits these methods from Foo1 and Foo2?

Advertisement

Answer

Have your class wrap Foo1 and Foo2 instances rather than using multiple inheritance.

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement