'Is there a way to create a class instance passing to the constructor a list of attributes? [duplicate]
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], ...., ....)
Solution 1:[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:
attributesis an iterable- 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. - You're making an assertion that the number of elements you can pull from
attributesmatches the argument count expected byFoo(sinceFootakes three arguments beyondself,attributesmust produce exactly three arguments, no more, no less)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
