【问题标题】:What is the function of __init__ method here [duplicate]__init__ 方法在这里的作用是什么[重复]
【发布时间】:2018-01-28 12:03:46
【问题描述】:
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方法用于调用超类的init方法进行初始化。
  • 看我的回答@Talmoor
  • 你完全不需要创建myThread 子类,你可以直接使用Thread 类,例如:mythread = threading.Thread(target=run1, args=('a', 'b')) mythread.start()。另见stackoverflow.com/questions/20736131/…

标签: python


【解决方案1】:

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

请注意,您明确调用threading.Thread,它是myThread 的基类。最好通过super(myThread, cls).__init__(self)引用父__init__方法。

Python 文档

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

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

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

【讨论】:

  • 为什么需要调用threading.Thread.__init__(self)
【解决方案2】:

这里发生的事情是,你从你的类 myThread 中的类 threading.Thread 继承。

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

所以你需要确保父类的__init__ 方法在执行你修改的__init__ 函数之前也运行。这就是为什么使用声明threading.Thread.__init__(self) 的原因。它只是调用父类的__init__ 方法。

【讨论】:

    猜你喜欢
    • 2013-06-02
    • 2013-07-27
    • 2011-04-22
    • 2011-10-09
    • 1970-01-01
    • 2011-02-25
    • 1970-01-01
    • 2012-03-24
    • 1970-01-01
    相关资源
    最近更新 更多