1

The "function"super() is useful in python for defining classes such as:

    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

the syntax object.method() and object.attribute is usually used in python but if super() really is a function, why does it use the same syntax? I've heard that in java it is a keyword, but I'm pretty sure that in python it is a function (because of the parentheses).

Natrium
  • 75
  • 6
  • 1
    If it were a keyword, this would be a syntax error: `super = 42` – juanpa.arrivillaga Jul 04 '20 at 23:29
  • I don't understand what you mean here: "but if `super()` really is a function, why does it use the same syntax" – juanpa.arrivillaga Jul 04 '20 at 23:32
  • since `super()` is used in a context such as `super().__init__(object)`, why is there a dot between `super()` and `__init__(object)`? (that syntax is usually used when the object name is to the left of the dot). – Natrium Jul 04 '20 at 23:40
  • because `super()` returns a `super` object, and you are accessing the `__init__` attribute on that super object. Just like `int().__init__`. Of course, `super` objects exist as proxy objects that provide the *next method in the method resolution order* – juanpa.arrivillaga Jul 04 '20 at 23:42

2 Answers2

2

Its actually a class, type(super) gives an output of <class 'type'>

Noob
  • 36
  • 2
0

As mentioned by others, super is a type, so when you invoke it with arguments, you just instantiate it. Supporting super without arguments requires it to know the current class lexically (using the class of self wouldn't work, as explained in this answer).

So, while super is not technically a keyword, it does get special treatment by the compiler. From 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.

user4815162342
  • 141,790
  • 18
  • 296
  • 355