Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I have to specify my own class when using super(), and is there a way to get around it?

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)?

like image 848
airportyh Avatar asked Jan 21 '09 19:01

airportyh


People also ask

How does super () work 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 does super () __ init __ do?

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.

How do you call a super class in Python?

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'.

Is super init necessary?

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.


2 Answers

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)
like image 108
nosklo Avatar answered Oct 24 '22 16:10

nosklo


The BDFL agrees. See PEP 3135 - New Super for Python 3.0 (and Pep 367 - New Super for Python 2.6).

like image 45
Peter Rowell Avatar answered Oct 24 '22 17:10

Peter Rowell