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 assuper(__class__, <first argument>)
super(type)
-> unbound super object
super(type, obj)
-> boundsuper
object; requiresisinstance(obj, type)
super(type, type2) -> bound super object; requires issubclass(type2, type)
[non-relevant examples redacted]
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.
__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.
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 ).
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With