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)
我知道 __init__ 用于初始化一个类,但下一行的目的是什么。是否有其他选择?
__init__
用于初始化类对象。当你创建一个新的myThread
对象时,它首先调用threading.Thread.__init__(self)
,然后定义两个属性str1和str2。
请注意,您显式调用了 threading.Thread
,它是 myThread
的基类。最好通过 super(myThread, cls).__init__(self)
引用父类 __init__
方法。
Python 文档
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.
派生类调用基类 init 有几个原因。
一个原因是如果基类在它的 __init__
方法中做了一些特殊的事情。你甚至可能没有意识到这一点。
另一个原因与OOP有关。假设您有一个基类和两个继承自它的子类。
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
这只是为了展示一个示例,但您可以看到 SportCar 和 MiniCar 对象如何使用 super(CURRENT_CLASS, cls).__init(self, PARAMS)
调用 Car 类来运行初始化基类中的代码。请注意,您还需要只在一个地方维护代码,而不是在每个类中重复它。