Python调用父方法多重继承 [英] Python Call Parent Method Multiple Inheritance

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

问题描述

所以,我有这样的情况。

So, i have a situation like this.

class A(object):
    def foo(self, call_from):
        print "foo from A, call from %s" % call_from


class B(object):
    def foo(self, call_from):
        print "foo from B, call from %s" % call_from


class C(object):
    def foo(self, call_from):
        print "foo from C, call from %s" % call_from


class D(A, B, C):
    def foo(self):
        print "foo from D"
        super(D, self).foo("D")

d = D()
d.foo()

代码结果为

foo from D
foo from A, call from D

调用所有父方法,在这种情况下,foo方法,从 D 类不使用父类 A 。我只想从 D 类调用super。类 A B C mixin类,我想从 D 调用所有foo方法。

I want to call all parent method, in this case, foo method, from D class without using super at the parent class like A. I just want to call the super from the D class. The A, B, and C class is just like mixin class and I want to call all foo method from D. How can i achieve this?

推荐答案

您可以使用 __ bases __

class D(A, B, C):
    def foo(self):
        print "foo from D"
        for cls in D.__bases__:
            cls().foo("D")

使用此更改,输出将为

foo from D
foo from A, call from D
foo from B, call from D
foo from C, call from D

这篇关于Python调用父方法多重继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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