Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

order of inheritance in Python classes

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'
like image 341
nluigi Avatar asked Jun 06 '26 17:06

nluigi


1 Answers

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!

like image 58
bearzk Avatar answered Jun 08 '26 07:06

bearzk