4

I have a class ExampleSim which inherits from base class Physics:

class Physics(object):
    arg1 = 'arg1'
    def physics_method:
        print 'physics_method'

class ExampleSim(Physics):
    print 'example physics sim'

Imagine these classes containing lots of code. Now I have made some modifications to Physics by defining a new class PhysicsMod and inheriting from Physics:

class PhysicsMod(Physics):
    arg1 = 'modified arg1'

but also to ExampleSim for which I created a new class ExampleSimMod and inherited from ExampleSim:

class ExampleSimMod(ExampleSim):
    print 'modified example sim'

My issue is that ExampleSimMod inherits from ExampleSim which inherits from Physics where i would like to have it inherit from PhysicsMod instead. Is there a way to do this? perhaps through super() or by multiple inheritance?

class ExampleSimMod(ExampleSim, PhysicsMod):
    print 'modified example sim'
Jeff Gruenbaum
  • 364
  • 6
  • 21
nluigi
  • 1,263
  • 2
  • 15
  • 35
  • Possible duplicate of [How does Python's super() work with multiple inheritance?](http://stackoverflow.com/questions/3277367/how-does-pythons-super-work-with-multiple-inheritance) – Łukasz Rogalski Dec 04 '15 at 13:57

1 Answers1

16

Yes, you can do multiple inheritance.

class Physics(object):
    def physics_method(self):
        print ('physics')

class ExampleSim(Physics):
    def physics_method(self):
        print ('example sim')

class PhysicsMod(Physics):
    def physics_method(self):
        print ('physics mod')

class ExampleSimMod(PhysicsMod, ExampleSim):
    pass

e = ExampleSimMod()
e.physics_method()
// output will be:
// physics mod

please note the order of class in ExampleSimMod matters. The's a great article about this.

I modified your code a bit for demonstration reason. Hope my answer can help you!

suhailvs
  • 20,182
  • 14
  • 100
  • 98
bearzk
  • 685
  • 3
  • 7
  • 22