2017-06-21 80 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()