506
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.

Flow
  • 23,572
  • 15
  • 99
  • 156
Mike
  • 58,961
  • 76
  • 175
  • 221
  • 1
    you should emphasize that an answer that doesn't use the Derived Class name is what you want. e.g. (pseudocode): `super().__init__(args...)` – Charlie Parker Jan 20 '20 at 17:04
  • 1
    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. – Charlie Parker Jan 20 '20 at 17:06
  • Python 2 is no longer officially supported. Also his answer came 5 years later. – Mike Jan 20 '20 at 17:15
  • 1
    @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.) – David Z Apr 05 '20 at 23:45
  • 1
    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()` – Mike Jun 23 '20 at 00:06

7 Answers7

445

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

Python 3

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

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

Python 2

In Python 2, 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__()
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Aidan Gomez
  • 8,167
  • 5
  • 28
  • 51
378

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()
kaya3
  • 47,440
  • 4
  • 68
  • 97
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • 87
    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? – Mike Mar 08 '10 at 04:48
  • 121
    No, because `self` might actually be an instance of `C`, a child of `B`. – Ignacio Vazquez-Abrams Mar 08 '10 at 04:50
  • 1
    What if `B(A, AA)`? I see that `super(B,self)` returns `A`, but then how do you get `AA`? – Iulius Curt Mar 13 '13 at 15:26
  • 2
    @iuliux: In that case, if `self` is an instance of `B`, then `super(B, self).__init__()` calls the method defined in `A` and `super(A, self).__init__()` calls the method defined in `AA`. If you're writing classes that might be multiply inherited from, you should always include a call to the `super` constructor, but which code that actually invokes depends on the inheritance decisions of your subclasses. See http://fuhm.net/super-harmful/ for more details. – Daniel Martin Jun 05 '13 at 19:50
  • 1
    Addition to the post: "new-style classes" means python3. – Luc Jul 21 '15 at 12:17
  • 1
    @Luc not quite. It's a term used in Python 2. [They were introduced in Python 2.2.](https://docs.python.org/2/reference/datamodel.html#new-style-and-classic-classes) You might be referring to the fact that they're the only available type of class in Python 3? – Dan Getz Jul 21 '15 at 12:50
  • @DanGetz I don't really know. All I observed was that my code (using `super(B,self).__init__(args)`) didn't work using python 2.7.6, but it does work using python 3.4.0. – Luc Jul 21 '15 at 14:49
  • 5
    @Luc: That's because the class was declared incorrectly. See my answer. – Ignacio Vazquez-Abrams Jul 21 '15 at 15:20
  • 1
    @IgnacioVazquez-Abrams Ah I see, there was no 'object' argument in A's constructor. My bad! – Luc Jul 21 '15 at 16:32
  • 28
    With respect to the [documentation of `super()`](https://docs.python.org/3/library/functions.html#super), you should be able to write `super().__init__()` wothout arguments. – JojOatXGME Apr 12 '16 at 15:02
  • 20
    @JojOatXGME: In 3.x, yes. 2.x still needs the arguments. – Ignacio Vazquez-Abrams Apr 12 '16 at 15:45
  • 2
    @IgnacioVazquez-Abrams Ok. Maybe you should mention that you are using python 2.x in your answer? I'm relative new to python and I think it is a little bit confusing that many sites do not write whether they are using python 2 or 3.? – JojOatXGME Apr 12 '16 at 15:57
  • The original post was written six years ago; python 3 was barely a thing at that point. – Andrew Hows Sep 12 '16 at 01:44
  • What is the rationale behind passing B (child Class) and self (child like object) to the super method? Ex.: super(B, self).__init__(). – router Jan 23 '17 at 10:11
  • 2
    @router: Python 2.x didn't use introspection in `super` to figure out what the relevant class and object were, so you had to pass them. – Ignacio Vazquez-Abrams Jan 23 '17 at 14:06
  • 2
    Why is the super function called last (I switching the order and python just ignored the code after the super_init, why is that?) – borgr Sep 05 '17 at 08:24
  • @borgr: Because we want "hello" to print before "world". If this isn't an issue in your code then call it whenever appropriate. – Ignacio Vazquez-Abrams Sep 05 '17 at 15:32
  • Finaly: what will the above code output? That should be added to the answer. – Danijel Nov 27 '19 at 07:40
  • your answer is the most viewed. Wouldn't it be useful to extend your answer to explain what is the best practice for python 3? I believe it's: don't use derived class name do this in python 3 (pseudocode): `super().__init__(args...)` – Charlie Parker Jan 20 '20 at 17:05
53

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)
Gabe
  • 84,912
  • 12
  • 139
  • 238
  • 6
    @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 Jun 03 '15 at 00:58
  • @Gabe That's one of the least important reasons to use `super`. – chepner Nov 21 '19 at 21:57
37

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).

bignose
  • 30,281
  • 14
  • 77
  • 110
Daniel Stutzbach
  • 74,198
  • 17
  • 88
  • 77
  • 1
    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. – Black Jack 21 May 10 '18 at 13:41
  • @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__`. – chepner Nov 21 '19 at 22:03
19

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.

gal007
  • 6,911
  • 8
  • 47
  • 70
  • 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 – Michael Wiles Apr 30 '20 at 10:19
17

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__(self):
    super(Base1, self).__init__()

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

class Derived(Base1, Base2):
  def __init__(self):
    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.

Czaporka
  • 2,190
  • 3
  • 10
  • 23
Shital Shah
  • 63,284
  • 17
  • 238
  • 185
  • `__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. – chepner Nov 21 '19 at 22:06
  • PyLint recommends using Python 3 style super() without arguments – Samuel Feb 16 '21 at 14:28
-1

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.

bignose
  • 30,281
  • 14
  • 77
  • 110
lackadaisical
  • 1,628
  • 18
  • 21
  • 11
    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`. – dened Jun 01 '16 at 08:11
  • 15
    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. – Martijn Pieters Sep 30 '16 at 16:25