2017-06-21 78 views
0

如果我定義了一個父類和子類,如下所示:「A」不能訪問方法的超類

class A(object): 
    def a_method(self): 
     print "A!" 

class B(A): 
    def b_method(self): 
     super(A, self).a_method() 
     print "B!" 

b_obj = B() 

我希望下面的打印出來和「B!」,但它會拋出一個錯誤:

b_obj = B() 

AttributeError: 'super' object has no attribute 'a_method' 

我很困惑。我錯過了什麼?

回答

1

因爲你想:

super(B, self).a_method() 

否則,你要跳過一個在mro

其他一切看起來都不錯。

+0

標誌着我你的答案是正確的,因爲你也提到的MRO,它回答了相關的問題我有。謝謝。 – PProteus

1

你應該在當前類傳遞給超,不超:

class B(A): 
    def b_method(self): 
     super(B, self).a_method() 
    #  ^
1

你應該做super(B, self)而不是super(A, self)。你需要訪問B的超類,而不是A的。

1

您需要將當前班級傳遞給super。從the official super documentation

super(type[, object-or-type])

Return a proxy object that delegates method calls to a parent or sibling class of type.

這是正確的代碼:

super(B, self).a_method()