【发布时间】: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