为什么super()。\uuuu init\uuuu没有自引用?

2024-09-30 22:18:06 发布

您现在位置:Python中文网/ 问答频道 /正文

当我们使用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


Tags: nameselfinitdefclassdepartmentmanagerssuper
1条回答
网友
1楼 · 发布于 2024-09-30 22:18:06

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.

重点补充

相关问题 更多 >