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)
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.
In python, super() is always called first in a method.
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.
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.
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