What is the function of __init__ method here

Question:

class myThread(threading.Thread):

    def __init__(self,str1,str2):
        threading.Thread.__init__(self)
        self.str1 = str1
        self.str2 = str2
    def run(self):
        run1(self.str1,self.str2)

I know the __init__ is used to initialize a class but What is the its purpose in the next line.Is there any alternative to this?

Asked By: Taimoor

||

Answers:

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

Answered By: Chen A.

Whats happening here is that , you are inheriting from the class threading.Thread in your class myThread.

So all the functions that are in the threading.Thread class are available in your inherited class and you are modifying the function __init__ in your class. So instead of running the init method of parent class , it will run __init__ method in your class.

So you need to make sure that the __init__ method of parent class also runs before executing your modified __init__ function. This is why the statement threading.Thread.__init__(self) is used . It just calls the __init__ method of the parent class.

Answered By: Natesh bhat
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.