Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In python, super() is always called first in a method. Are there situations where it should be called later?

Tags:

python

super

Are there situations where you want to do some processing before you call super()?

This is a contrived example. Are there better examples? Is this considered pythonic?

class Base(object):     def __init__(self, name):         print "Base %s created" % name         self._name = name  class UpperBase(A):     """ Similar to base but the name is in uppercase. """     def __init__(self, name):         name = name.upper()          super(UpperBase, self).__init__(name) 
like image 372
TomOnTime Avatar asked Apr 12 '11 11:04

TomOnTime


People also ask

Does super () init have to be first?

If the class you're super ing requires the object to be in a certain state then you put it in that state before super ... If your class requires the object to be in a certain state before it can continue its initialisation and that's provided by a parent class then you super that first.

Does Super have to be first line Python?

In python, super() is always called first in a method.

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 is super () __ Init__ 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.


1 Answers

Sometimes you need to validate the arguments before calling super():

class UpperBase(Base):     def __init__(self, name):         if not name_valid(name):             raise ValueError()         super(UpperBase, self).__init__(name) 

I don't see why this wouldn't be pythonic, because it's the easiest way to do it and it's straightforward. Also, read @JHSaunders' comment, he makes a good point.

like image 127
Gabi Purcaru Avatar answered Nov 08 '22 21:11

Gabi Purcaru