1

Using a keyword argument when creating an instance of a class, followed by *args, leads to an error. However, without this, the readability is impaired. Notice the a= when creating the instance in the second example.

This works:

class ExampleClass:
    def __init__(self, a, *args):
        self.a = a

args = [1]

example_instance = ExampleClass(None, *args)

print(example_instance.a)

>>> None

While this does not work:

class ExampleClass:
    def __init__(self, a, *args):
        self.a = a

args = [1]

example_instance = ExampleClass(a=None, *args)

print(example_instance.a)

>>> Traceback (most recent call last):
>>>   File "C:/Users/test.py", line 63, in <module>
>>>     example_instance = ExampleClass(a=None, *args)
>>> TypeError: __init__() got multiple values for argument 'a'
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
cheesus
  • 1,111
  • 1
  • 16
  • 44
  • 1
    you can't use `a=` because a isn't a named argument [This](https://stackoverflow.com/questions/3394835/use-of-args-and-kwargs) page may help explain more – badger0053 Jan 08 '20 at 15:32
  • 1
    `def __init__(*args, a)` then you can do `ExampleClass(*args, a=None)` – Giacomo Alzetta Jan 08 '20 at 15:37
  • 3
    @badger0053 `a` *is* a named parameter; that's the problem. You are specifying a positional argument (via `*args`) that would be matched to `a` *and* a keyword argument to set `a`; that's not allowed. – chepner Jan 08 '20 at 15:41
  • 1
    @badger0053 (I should say, the OP is specifying a positional parameter, not you.) – chepner Jan 08 '20 at 15:46

0 Answers0