为什么super().__init__没有self引用?

3
为什么在使用 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


1
出于同样的原因,当您调用其他方法时,无需传递“self”。 - Mark
2
@MarkMeyer。不完全正确。Super 是特殊的。 - Mad Physicist
1
@MarkMeyer 但你确实需要编写 self.method(...)super 使用一些魔法来避免必须指定 self - interjay
在 Python 2 中,你必须编写 super(managers, self)。在 Python 3 中对此进行了更改以使其自动化。 - Barmar
1
@interjay 我认为这个问题是在询问为什么不需要使用 super().__init__(self, name,department,salary),答案是像调用方法一样,Python 会自动执行它。 - Mark
1个回答

4

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

Replacing the old usage of super, calls to the next class in the MRO (method resolution order) can be made without explicitly passing the class object (although doing so will still be supported). Every function will have a cell named __class__ that contains the class object that the function is defined in.

The new syntax:

super()

is equivalent to:

super(__class__, <firstarg>)

[...]

While super is not a reserved word, the parser recognizes the use of super in a method definition and only passes in the __class__ cell when this is found. Thus, calling a global alias of super without arguments will not necessarily work.

已加强说明。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接