7

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

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 this for a case of diamond-inheritance.)

According to super's documentation, it seems like what I want should be possible. This is super's documentation: (Emphasis mine)

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

super(type) -> unbound super object

super(type, obj) -> bound super object; requires isinstance(obj, type)

super(type, type2) -> bound super object; requires issubclass(type2, type)

[non-relevant examples redacted]

1
  • I deleted my answer - I got the same error. Very strange, will look into it a little more. Commented Jan 13, 2011 at 22:54

2 Answers 2

8

It looks as though you need an instance of B to pass in as the second argument.

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

Sign up to request clarification or add additional context in comments.

1 Comment

+1, Good read, part 2/3 of this article series describes the exact problems and real use case for unbound super objects: artima.com/weblogs/viewpost.jsp?thread=236278 (The secrets of unbound super objects)
6

According to this it seems like 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 

3 Comments

Glad the linked source helped. :)
Remember that this will give you unbound methods; the reason you normally need to say super(B, self) is to get a super object bound to an object, to retrieve bound methods.
... this looks really weird to me but works perfectly in Python 2.7.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.