Python super :
Python super keyword is confusing some time to newbie or even for intermediate python programmers.
But the idea behind super is really simple. In OOP paradigm we often need to do implement inheritance like below:
print 'Fancy Function Called from Class A'
return super(B, self).fancy_func()
b is an Object of class B and fancy_func is the method of B, super is returning the base classes method. If we don’t use super,we had declare an object of class A and then we had to call fancy_func. On the other hand,super returns proxy object. Super uses __mro__(method resolution order).
Super can be used:
- For single inheritance using to refer parent classes
- In multiple inheritance its very useful in during dynamic execution.
For real life coding when we need to enhance any module method we can easily super to get things done.
And we don’t even have to know details about the base class that we are extending from.
super is only applicable for python new style classes ( the classes derived from object ex. class A(object) )
For python3 the syntax is like below:
Syntax of calling super is like below:
Python __init__ :
If you declare a __init__ in your python class, it will be run when you initialize an object from that class.
__init__ acts like constructors in other languages but actually its not. There is a basic major difference between from other methods and __init__,its you cant return anything from it.You can add properties to the current object using like self.myProperty = ‘TEST’ and you can use it in any other method by accessing like self.myProperty
Simply __init__ is used when we want to control the initialization of the class.
Lets build something real with these features:
In the above example we implement both the concept of __init__ and super. Here __init__ using for setting value of url while intilazing the object and super is being used to call the crawlPyCentral’s getTitles.
To dig more deep into super check this blog post