为什么我们在使用 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
在这种情况下,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.
添加了强调。