When using Python's super()
to do method chaining, you have to explicitly specify your own class, for example:
class MyDecorator(Decorator):
def decorate(self):
super(MyDecorator, self).decorate()
I have to specify the name of my class MyDecorator
as an argument to super()
. This is not DRY. When I rename my class now I will have to rename it twice. Why is this implemented this way? And is there a way to weasel out of having to write the name of the class twice(or more)?
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.
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.
Using Super(): Python super() function provides us the facility to refer to the parent class explicitly. It is basically useful where we have to call superclass functions. It returns the proxy object that allows us to refer parent class by 'super'.
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 ). It typically creates its underlying data structure.
In Python 3.0, you can use super()
which is equivalent to super(ThisClass, self)
.
Documentation here. Code sample from the documentation:
class C(B):
def method(self, arg):
super().method(arg)
# This does the same thing as: super(C, self).method(arg)
The BDFL agrees. See PEP 3135 - New Super for Python 3.0 (and Pep 367 - New Super for Python 2.6).
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