python - 这里__init__方法的作用是什么

标签 python

<分区>

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 类来运行初始化基类中的代码。请注意,您还需要只在一个地方维护代码,而不是在每个类中重复它。

关于python - 这里__init__方法的作用是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45779729/

相关文章:

python - 是否有 django 的 'hello world' 网站?或者(我已经安装了 django,现在是什么)?

python - 使用 python 和 gmail 在同一个线程中发送多封电子邮件

python - 将一个列表分成两个列表

python - OpenCV 绘制轮廓错误断言失败

python - Django 1.8 csrf名称错误: Undefined

python - 在法国的 Windows 服务器上使用 django 的换行符问题

python - 使用 re (雷鬼) 在 python 中查找模式

python - 类型错误 : Can't convert 'bytes' object to str implicitly despite adding . 编码()到字符串

c# - 英特尔的开源 uPNP SDK 有绝对 0 的文档,为什么?

python - 自定义用户模型 Django TypeError : create_user() missing 1 required positional argument: 'username'