天天看點

python多重繼承 同名函數_在多重繼承中,python如何繼承/重寫函數?[副本]

我有以下代碼:

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不工作?

我假設函數按照我在繼承中提到的順序從左到右填充在類的dict中。但是,它似乎是從右向左的?