【问题标题】:How does python inherit/override functions in multiple inheritence? [duplicate]python如何在多重继承中继承/覆盖函数? [复制]
【发布时间】:2019-01-04 17:29:33
【问题描述】:

我有以下代码:-

class A(object):
    def __init__(self):
        print "I'm in A"

    def awesome_function(self):
        raise NotImplementedError

class B(A):
    def awesome_function(self):
        print "Implemented in B"

class C(object):
    def awesome_function(self):
        print "Implemented in C"

class D(A,C):
    def another_function(self):
        print "hello world"

class E(C,A):
    def another_function(self):
        print "hello world"

try:
    a = A()
    a.awesome_function()
except Exception as e:
    print "NotImplementedError"
    pass

try:
    b = B()
    b.awesome_function()
except Exception as e:
    print "NotImplementedError in b"

try:
    d = D()
    d.awesome_function()
except Exception as e:
    print "NotImplementedError in d"

try:
    e = E()
    e.awesome_function()
except Exception as s:
    print "NotImplementedError in e"

我得到的输出是:-

I'm in A
NotImplementedError
I'm in A
Implemented in B
I'm in A
NotImplementedError in d
I'm in A
Implemented in C

为什么E有效而D无效?

我假设函数按照我在继承中提到的顺序从左到右填充到类的字典中。不过好像是从右往左走?

【问题讨论】:

  • 如您所见,继承是一个堆栈(后进先出...即从右到左)

标签: python inheritance multiple-inheritance virtual-functions abstraction


【解决方案1】:

可以查看方法解析顺序:

print D.__mro__
(<class '__main__.D'>, <class '__main__.A'>, <class '__main__.C'>, <type 'object'>)
print E.__mro__  
(<class '__main__.E'>, <class '__main__.C'>, <class '__main__.A'>, <type 'object'>)

如您所见,D 类首先进入超类 A(并找到了 awesome_function 方法),这是您在继承中从左到右列出的顺序。

【讨论】:

    猜你喜欢
    • 2012-04-13
    • 1970-01-01
    • 1970-01-01
    • 2019-06-29
    • 2011-01-10
    • 1970-01-01
    • 2019-06-19
    • 2011-09-04
    • 2017-09-30
    相关资源
    最近更新 更多