Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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]

like image 639
Ram Rachum Avatar asked Jan 13 '11 22:01

Ram Rachum


People also ask

How do you Super A class in Python?

The super() function in Python makes class inheritance more manageable and extensible. The function returns a temporary object that allows reference to a parent class by the keyword super. The super() function has two major use cases: To avoid the usage of the super (parent) class explicitly.

What is super () __ Init__?

__init__() Call in Python. When you initialize a child class in Python, you can call the super(). __init__() method. This initializes the parent class object into the child class. In addition to this, you can add child-specific information to the child object as well.

Is super () necessary Python?

In general it is necessary. And it's often necessary for it to be the first call in your init. It first calls the init function of the parent class ( dict ).

How do you call a super method in Python?

Super() to Call Super Class Constructor Here, the derived class Newdemo calls the super() with arguments a, b, and c. This causes the constructor __init__ of the base class, i.e. Demo to be called. This initialises the values of a, b, and c. Hence, the Newdemo class no longer initialises the values itself.


2 Answers

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

like image 97
James Avatar answered Oct 18 '22 12:10

James


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
like image 28
Ram Rachum Avatar answered Oct 18 '22 11:10

Ram Rachum