0

When I extend a parent class which has a **kwargs, I can not write kwargs in super(ParentClass, self).__init__(args, kwargs). Why is it like this?

Code as follows: Originally I think below is right, but it is not.

class Parent(object):
  def __init__(self, *args, **kwargs):
    pass

class Child(Parent):
  def __init__(self, *args, **kwargs):
    super(Child, self).__init__(args, kwargs)

In fact, below it is right after I test.

class Parent(object):
  def __init__(self, *args, **kwargs):
    pass

class Child(Parent):
  def __init__(self, *args, **kwargs):
    super(Child, self).__init__(*args, **kwargs)

When we reference a arg like *args, **kwargs, usually we directly use args, kwargs. Why here when I write a __init__, I can not do that?

evolever
  • 29
  • 2
  • 10

1 Answers1

0

You need to use

class Child(Parent):
  def __init__(self, *args, **kwargs):
    super(Child, self).__init__(*args, **kwargs)

In order to unpack the kwargs (and args)

And your second issue is that the first argument of the init should be self which is the instance.

When you do super(Child, self).something you're basically saying we call something on the parent instance.

When you do __init__(*args, **args) the first argument is the instance (in your case args[0]). So super(Child, self).__init__(*args[1:], **kwargs) would have worked but it's better (way better) to use self and it'll work.

astreal
  • 3,383
  • 21
  • 34
  • The OP is (I think) asking *why* that is. Note that they are *already* doing this in their question! – Martijn Pieters Oct 11 '14 at 08:50
  • sorry. i changed it. my question not that self in fact. – evolever Oct 11 '14 at 09:10
  • my question is when we call another function, we use a actual arg to pass. like **kwargs, i think kwargs is the actual arg, why we can't directly pass kwargs here. – evolever Oct 11 '14 at 09:12
  • then you should probably read http://stackoverflow.com/questions/36901/what-does-double-star-and-star-do-for-python-parameters. Basically kwargs is a dictionary, but when **-operator is used it unpacks the key, value into named parameters for a function. if you don't use the `**` then your basically just passing a single parameter which is a dict. – astreal Oct 11 '14 at 09:19