Python类中的继承顺序 [英] order of inheritance in Python classes

查看:42
本文介绍了Python类中的继承顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类 ExampleSim ,它从基类 Physics 继承:

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'

想象一下这些包含大量代码的类.现在,我通过定义新类 PhysicsMod 并从 Physics 继承来对 Physics 进行了一些修改:

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'

,但同时也是 ExampleSim 的示例,为此我创建了一个新类 ExampleSimMod 并从 ExampleSim 继承:

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

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

我的问题是, ExampleSimMod 是从 ExampleSim 继承的,而 ExampleSim 是从 Physics 继承的,而我希望它是从 PhysicsMod .有没有办法做到这一点?可能是通过 super()还是通过多重继承?

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'

推荐答案

是的,您可以进行多重继承.

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

请注意 ExampleSimMod 中类的顺序很重要.这是出色的文章.

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!

这篇关于Python类中的继承顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆