ChatGPT解决这个技术问题 Extra ChatGPT

How to invoke the super constructor in Python?

class A:
    def __init__(self):
        print("world")

class B(A):
    def __init__(self):
       print("hello")

B()  # output: hello

In all other languages I've worked with the super constructor is invoked implicitly. How does one invoke it in Python? I would expect super(self) but this doesn't work.

you should emphasize that an answer that doesn't use the Derived Class name is what you want. e.g. (pseudocode): super().__init__(args...)
you should be accepting Aidan Gomez's answer. It would save us a lot of time, since it has an answer in both python 2 and 3.
Python 2 is no longer officially supported. Also his answer came 5 years later.
@Mike I think there's still value in an answer that lists the Python 2 way, because there's a lot of old Python 2 code floating around out there, and some of the people who wind up at this question probably won't otherwise know how to make sense of it. (And despite it being EOL, many people do still write code in Python 2, either because they don't know better or because some organizational requirement has forced it on them.)
I have changed the accepted answer to @Aiden Gomez's answer. Though Ignacio was correct, @Aidan's was the most appropriate as of today given Python 3's changes to super()

N
Neuron

In line with the other answers, there are multiple ways to call super class methods (including the constructor), however in Python-3.x the process has been simplified:

Python-3.x

class A(object):
 def __init__(self):
   print("world")

class B(A):
 def __init__(self):
   print("hello")
   super().__init__()

Python-2.x

In python 2.x, you have to call the slightly more verbose version super(<containing classname>, self), which is equivalent to super()as per the docs.

class A(object):
 def __init__(self):
   print "world"

class B(A):
 def __init__(self):
   print "hello"
   super(B, self).__init__()

k
kaya3

super() returns a parent-like object in new-style classes:

class A(object):
    def __init__(self):
        print("world")

class B(A):
    def __init__(self):
        print("hello")
        super(B, self).__init__()

B()

just of curiosity why does super(B,self) require both B and self to be mentioned? isn't this redundant? shouldn't self contain a reference to B already?
No, because self might actually be an instance of C, a child of B.
@Luc: That's because the class was declared incorrectly. See my answer.
With respect to the documentation of super(), you should be able to write super().__init__() wothout arguments.
@JojOatXGME: In 3.x, yes. 2.x still needs the arguments.
G
Gabe

With Python 2.x old-style classes it would be this:

class A: 
 def __init__(self): 
   print "world" 

class B(A): 
 def __init__(self): 
   print "hello" 
   A.__init__(self)

@kdbanman: This will work with new-style classes, but one of the reasons to use new-style classes is to not have to do it this way. You can use super and not have to directly name the class you're inheriting from.
@Gabe That's one of the least important reasons to use super.
b
bignose

One way is to call A's constructor and pass self as an argument, like so:

class B(A):
    def __init__(self):
        A.__init__(self)
        print "hello"

The advantage of this style is that it's very clear. It call A's initialiser. The downside is that it doesn't handle diamond-shaped inheritance very well, since you may end up calling the shared base class's initialiser twice.

Another way is to use super(), as others have shown. For single-inheritance, it does basically the same thing as letting you call the parent's initialiser.

However, super() is quite a bit more complicated under-the-hood and can sometimes be counter-intuitive in multiple inheritance situations. On the plus side, super() can be used to handle diamond-shaped inheritance. If you want to know the nitty-gritty of what super() does, the best explanation I've found for how super() works is here (though I'm not necessarily endorsing that article's opinions).


Is there any need to call A's constructor like this when it doesn't take any variable(ignoring self) as an argument? I mean the code works fine without A.__init__(self) line.
@RedFloyd It depends on what A.__init__ actually does. It may initialize various internal attributes in a constant fashion (self.stuff = [], e.g.), which may cause your instance of B to not behave correctly if you don't call A.__init__.
b
bignose

Short Answer

super(DerivedClass, self).__init__()

Long Answer

What does super() do?

It takes specified class name, finds its base classes (Python allows multiple inheritance) and looks for the method (__init__ in this case) in each of them from left to right. As soon as it finds method available, it will call it and end the search.

How do I call init of all base classes?

Above works if you have only one base class. But Python does allow multiple inheritance and you might want to make sure all base classes are initialized properly. To do that, you should have each base class call init:

class Base1:
  def __init__():
    super(Base1, self).__init__()

class Base2:
  def __init__():
    super(Base2, self).__init__()

class Derived(Base1, Base2):
  def __init__():
    super(Derived, self).__init__()

What if I forget to call init for super?

The constructor (__new__) gets invoked in a chain (like in C++ and Java). Once the instance is created, only that instance's initialiser (__init__) is called, without any implicit chain to its superclass.


__new__ isn't chained, either. If all three classes in your example defined __new__, but didn't use super().__new__(), then Derived() would call Derived.__new__ but not Base1.__new__ or Base2.__new__. A __new__ that doesn't call its parent's __new__ is almost useless, though, because ultimately object.__new__ is the only thing that truly creates a new instance of anything.
PyLint recommends using Python 3 style super() without arguments
g
gal007

Just to add an example with parameters:

class B(A):
    def __init__(self, x, y, z):
        A.__init__(self, x, y)

Given a derived class B that requires the variables x, y, z to be defined, and a superclass A that requires x, y to be defined, you can call the static method init of the superclass A with a reference to the current subclass instance (self) and then the list of expected arguments.


this is a more correct answer as the class that renders as super() can change... this makes it clear which constructor you want to call
b
bignose

I use the following formula that extends previous answers:

class A(object):
 def __init__(self):
   print "world"

class B(A):
 def __init__(self):
   print "hello"
   super(self.__class__, self).__init__()

B()

This way you don't have to repeat the name of the class in the call to super. It can come handy if you are coding a large number of classes, and want to make your code in the initialiser methods independent of the class name.


But you will get infinitive recursion if decide to extend B with C, and self.__class__ points to C(B) instead of B(A), so super(self.__class__, self) points back to B instead of A.
This will lead to infinite recursion errors when you subclass B. Do not use self.__class__ or type(self), either pass in an explicit class (B here) or, in Python 3, use super() without arguments.