0

Say I have the following

class ClassA (object):
  def meth1() ..

class ClassB (ClassA):
 def meth1() ..
 def meth2() ..
 def meth3() .. 

class ClassC (ClassB): 
 calls meth2() and meth(3) 

I am trying to refactor ClassC to make it inherit from ClassA instead. However, ClassC uses two important methods from ClassB that I don't want to rewrite, they have to stay under ClassB. Also, I don't want meth1 in ClassA to be overwritten by ClassB. Is there a way to call meth2 and meth3 from ClassB in ClassC and make ClassC inherit ClassA and use meth1 from ClassA? I hope my explanation is clear. And I'd appreciate it if you direct me to some documentation about this.

1
  • It's not really clear; could you give a less abstract minimal reproducible example? Note that Python does support multiple inheritance, although that's not always the right approach. Commented May 24, 2016 at 17:18

2 Answers 2

1

Make ClassC a subclass of both ClassA and ClassB:

class ClassC (ClassA, ClassB): 
   #calls meth2() and meth3() 

ClassC().meth1() will call ClassA's meth1, while ClassC().meth2() and ClassC().meth3() would call ClassB's methods, since methods not defined in ClassC are looked-up in the base classes in order.

The order in which bases classes are searched is governed by the method resolution order (MRO). For more on MRO see Michele Simionato's article and Shalabh Chaturvedi's article.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! so to make sure I understand, the method calls in ClassC will first look for the method definition in ClassC, then ClassA, then ClassB right?
0

If the methods absolutely NEED to stay under their original classes, I would probably go with multiple inheritance, though I would likely need more information on the specifics of the project to say so definitely.

class ClassC(ClassA, ClassB):
           ... code here ...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.