What is the function of

This question already has an answer here:

  • Understanding Python super() with __init__() methods [duplicate] 7 answers
  • How to invoke the super constructor? 5 answers
  • What does 'super' do in Python? 5 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.


    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.

    链接地址: http://www.djcxy.com/p/30044.html

    上一篇: Python从列表继承

    下一篇: 什么是功能