super() 是函数还是关键字?

Is super() a function or a keyword?

“函数”super() 在 python 中非常有用,可用于定义 类,例如:

    class Parent:
        def __init__(self, trait):
            self.trait = trait

    class Child(Parent):
        def __init__(self, primary_trait, secondary_trait):
            super().__init__(primary_trait)
            self.secondary_trait = secondary_trait

语法object.method()object.attribute通常在python中使用,但如果super()真的是一个函数,为什么它使用相同的语法?我听说在 java 中它是一个关键字,但我很确定在 python 中它是一个函数(因为有括号)。

它实际上是一个class,type(super)给出了<class 'type'>

的输出

正如其他人所说,super是一种类型,所以当你用参数调用它时,你只是实例化它。支持不带参数的 super 需要它在词法上知道当前的 class(使用 self 的 class 是行不通的,如 in this answer 所解释的)。

因此,虽然 super 在技术上不是关键字,但它 确实 得到编译器的特殊处理。来自 PEP 3135:

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.