9

What is the difference between these two code samples?

1:

class SubType(type):
    def __init__(cls, name, bases, dct):
        super().__init__(name, bases, dct)

2:

class SubType(type):
    def __init__(cls, name, bases, dct):
        pass
jvperrin
  • 3,368
  • 1
  • 23
  • 33
user2909276
  • 91
  • 1
  • 1
  • 6

4 Answers4

7

In python 3.x it means calling the __init__ method of the superclass (i.e. type) (as if it were a method of the current class, SubType, since the current class is a derived of the superclass).

It is the same as calling super(type, self).__init__() in Python 2.x

For example:

class type:
       def __init__(self, a):
           print(a)

 class SubType(type):
       def __init__(self, a):
           super().__init__(a)

>> obj = SubType(2) 
2
>>
Mihai Andrei
  • 169
  • 3
  • 13
4

in one case you are calling the __init__ method of the base class for all classes (i.e. type) - and in th e other you aren't.

Since this method does nothing by default, there is effectively no difference between the two listings.

(What really performs the class creation magic is the metaclass __new__ method - and it is not possible to have a new object in Python without calling a native base metaclass'__new__method.

jsbueno
  • 99,910
  • 10
  • 151
  • 209
0

Super lets you avoid referring to the base class explicitly, which can be nice. But the main advantage comes with multiple inheritance, where all sorts of fun stuff can happen. See the standard docs on super if you haven't already.

Gudron Swiss
  • 445
  • 1
  • 4
  • 6
-2

The code in block 1 will break in Python 2 but will pass in Python 3. The code in block 2 will pass for both.

Barry Hammer
  • 183
  • 6