Question

What's the diffeernce between super(SomeClass, self).__init__() AND super(SomeClass, self).__init__(*args, **kwargs)? The first one initializes the constructor of the parent, but what about the second one?

Was it helpful?

Solution

The second one calls the superclass' constructor with arguments.

Some demonstration:

>>> class Base(object):
...     def __init__(self, arg1, arg2, karg1=None, karg2=None):
...             print arg1, arg2, karg1, karg2
... 
>>> b = Base(1, 2, karg2='a')
1 2 None a
>>> class Derived(Base):
...     def __init__(self, *args, **kwargs):
...             super(Derived, self).__init__(*args, **kwargs)
... 
>>> d = Derived(1, 2, karg1='Hello, world!')
1 2 Hello, world! None

>>> class Derived2(Base):
...     def __init__(self):
...             super(Derived2, self).__init__()        # this will fail because Base.__init__ does not have a no-argument signature
... 
>>> d2 = Derived2()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __init__
TypeError: __init__() takes at least 3 arguments (1 given)

OTHER TIPS

super(SomeClass, self) returns a proxy object that stands in for some class (not necessarily the parent of SomeClass, if multiple inheritance is involved). As such, you need to pass the appropriate argument to its __init__ method. If it expects arguments, the first will fail. If it expects no arguments, the second one may fail, if args and kwargs aren't already empty.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top