-2

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?

Ahmed Sadman
  • 105
  • 10
  • 3
    This question keeps cropping up. The answer is the same each and every time, you are getting hung up over the `*args` and `**kwargs` syntax, not about `__init__` methods here. – Martijn Pieters May 08 '14 at 18:40
  • 2
    See [Argument List Unpacking](https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists). – Lukas Graf May 08 '14 at 18:41
  • @MartijnPieters Thanks for your comment. I actually know about those STARS, and I have already told that. I am not a pro programmer, but it doesn't mean that I am too stupid to ask the same question again and again. Look at my elected BEST ANSWER, it clearly answers my question. – Ahmed Sadman May 08 '14 at 18:55

2 Answers2

3

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)
Santa
  • 11,381
  • 8
  • 51
  • 64
1

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.

chepner
  • 497,756
  • 71
  • 530
  • 681