__init__
is used to initialize class objects. When you create a new object of myThread
, it first calls threading.Thread.__init__(self)
and then defines two attributes str1 and str2.
Note that you explicity call threading.Thread
, which is the base class of myThread
. It is better to refer the parent __init__
method by super(myThread, cls).__init__(self)
.
Python docs
There are two typical use cases for super. In a class hierarchy with single inheritance, super can be used to refer to parent classes without naming them explicitly, thus making the code more maintainable. This use closely parallels the use of super in other programming languages.
The second use case is to support cooperative multiple inheritance in a dynamic execution environment.
There are couple reasons derived classes calls base classes init.
One reason is if the base class does something special in it's __init__
method. You may not even be aware of that.
The other reason is related to OOP. Let's say you have a base class and two subclasses that inherits from it.
class Car(object):
def __init__(self, color):
self.color = color
class SportCar(car):
def __init__(self, color, maxspeed):
super(SportCar, cls).__init__(self, color)
self.maxspeed = maxspeed
class MiniCar(car):
def __init__(self, color, seats):
super(MiniCar, cls).__init__(self, color)
self.seats = seats
This is just to show an example, but you can see how both SportCar and MiniCar objects calls Car class using the super(CURRENT_CLASS, cls).__init(self, PARAMS)
to run the initialize code in the base class. Note that you also need to maintain the code only in one place instead of repeating it in every class.