Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 这里uuu init_uuu方法的功能是什么_Python - Fatal编程技术网

Python 这里uuu init_uuu方法的功能是什么

Python 这里uuu init_uuu方法的功能是什么,python,Python,我知道\uuuuu init\uuuuuu用于初始化类,但下一行中它的用途是什么。有什么替代方法吗?用于初始化类对象。当您创建一个新的myThread对象时,它首先调用threading.Thread.\uu_init\uuuu(self),然后定义两个属性str1和str2 请注意,您明确地调用了threading.Thread,它是myThread的基类。最好通过super(myThread,cls)引用父\uuuuu init\uuuu方法 Python文档 super有两个典型用例。在具

我知道\uuuuu init\uuuuuu用于初始化类,但下一行中它的用途是什么。有什么替代方法吗?

用于初始化类对象。当您创建一个新的
myThread
对象时,它首先调用
threading.Thread.\uu_init\uuuu(self)
,然后定义两个属性str1和str2

请注意,您明确地调用了
threading.Thread
,它是
myThread
的基类。最好通过
super(myThread,cls)引用父
\uuuuu init\uuuu
方法

Python文档

super有两个典型用例。在具有单一继承的类层次结构中,super可用于引用父类,而无需显式命名它们,从而使代码更易于维护。这种用法与super在其他编程语言中的用法非常相似

第二个用例是在动态执行环境中支持协作多重继承

派生类调用基类init有两个原因。 一个原因是如果基类在它的
\uuuu init\uuu
方法中做了一些特殊的事情。你甚至可能没有意识到这一点。 另一个原因与OOP有关。假设有一个基类和两个子类继承自它

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)

这只是一个示例,但您可以看到SportCar和MiniCar对象如何使用
super(当前_类,cls)。\uu init(self,PARAMS)
在基类中运行初始化代码。请注意,您还需要只在一个地方维护代码,而不是在每个类中重复代码。

这里发生的是,您继承了类
threading.Thread中的类
Thread

因此
threading.Thread
类中的所有函数都可以在继承的类中使用,并且您正在修改类中的函数
\uuuu init\uuu
。因此,它不会运行父类的init方法,而是在您的类中运行
\uuuu init\uuu
方法


因此,您需要确保父类的
\uuuuu init\uuu
方法在执行修改后的
\uuuuu init\uu
函数之前也会运行。这就是为什么要使用语句
threading.Thread.\uuu init\uuuu(self)
。它只调用父类的
\uuuuu init\uuuuu
方法。

第二个init方法用于调用超级类的init方法进行初始化。参见我的答案@Talmoor您完全不需要创建
myThread
子类,您只需使用
Thread
类本身,例如:
myThread=threading.Thread(target=run1,args=('a','b'))
mythread.start()
。另请参见为什么需要调用threading.Thread.\uu init\uuuu(self)
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