【问题标题】:Why super().__init__ doesn't have a self-reference? [duplicate]为什么 super().__init__ 没有自引用? [复制]
【发布时间】:2020-07-30 09:16:07
【问题描述】:

为什么我们在使用super().__init__?的时候不需要自引用(比如下面的第9行)

class labourers():
    def __init__(self,name,department,salary):
        self.name = name
        self.department = department
        self.salary = salary

class managers(labourers):
    def __init__(self,name,department,salary,numberofpeople):
        super().__init__(name,department,salary)
        self.numberofpeople = numberofpeople

【问题讨论】:

  • 出于同样的原因,您在调用其他方法时不必传递self
  • @MarkMeyer。不完全是。超级是特别的。
  • @MarkMeyer 但是你必须写self.method(...)super 使用了一些魔法来避免必须指定 self
  • 在 Python 2 中,您必须编写 super(managers, self)。它在 Python 3 中进行了更改以使其自动化。
  • @interjay 我的问题是问你为什么不需要super().__init__(self, name,department,salary) 答案是,就像方法调用一样,python 会为你做。

标签: python python-3.x oop super


【解决方案1】:

在这种情况下,Super 的功能是在 CPython 解析器中实现的。见PEP 3135

取代 super 的旧用法,可以在不显式传递类对象的情况下调用 MRO(方法解析顺序)中的下一个类(尽管仍然支持这样做)。每个函数都有一个名为 __class__ 的单元格,其中包含定义函数的类对象。

新语法:

super()

相当于:

super(__class__, <firstarg>)

[...]

虽然 super 不是保留字,解析器会识别方法定义中使用 super 并仅在找到时传入 __class__ 单元格。 因此,调用 super 的全局别名时无需论据不一定有效。

添加了重点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-29
    • 2021-11-26
    • 1970-01-01
    • 2021-04-30
    • 1970-01-01
    • 2018-11-05
    • 2013-06-02
    • 2013-06-20
    相关资源
    最近更新 更多