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