0

Let's say I have this class

class Foo:

    def __init__(self, a, b, c):
         self.a = a
         self.b = b
         self.c = c

Is there a way to make a shortcut in the constructor arguments so I don't need to explicitly pass every parameter from a list, for example:

def main():
    attributes = [1,2,3]
    foo = Foo(attributes) #instead of Foo(attributes[0], ...., ....)
martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

1

Just use iterable-unpacking to pass your list of arguments as sequential positional arguments:

def main():
    attributes = [1,2,3]
    foo = Foo(*attributes)

The * in front of attributes in the call means:

  1. attributes is an iterable
  2. It should be unpacked such that the first element becomes the first positional argument (after the implied self), the second element the second positional argument, etc.
  3. You're making an assertion that the number of elements you can pull from attributes matches the argument count expected by Foo (since Foo takes three arguments beyond self, attributes must produce exactly three arguments, no more, no less)
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271