Python: Why can't I use `super` in a class?

Why can't I use super to get the superclass method of a class?

Example:

 Python 3.1.3 >>> class A(object): ... def my_method(self): pass >>> class B(A): ... def my_method(self): pass >>> super(B).my_method Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> super(B).my_method AttributeError: 'super' object has no attribute 'my_method' 

(Of course, this is a trivial case where I could just do A.my_method , but I needed it for the case of diamond inheritance.)

According to the super documentation, it looks like I want this to be possible. This is super documentation: (Emphasis mine)

super() same as super(__class__, <first argument>)

super(type) unrelated super object

super(type, obj) → bound super object; requires isinstance(obj, type)

super (type, type2) → related super object; requires issubclass (type2, type)

[irregular examples edited]

+7
source share
2 answers

Accordingly, it seems that I just need to call super(B, B).my_method :

 >>> super(B, B).my_method <function my_method at 0x00D51738> >>> super(B, B).my_method is A.my_method True 
+7
source

It looks like you need instance B to be passed as the second argument.

http://www.artima.com/weblogs/viewpost.jsp?thread=236275

+8
source

All Articles