saul.shanabrook
saul.shanabrook

Reputation: 3168

Create class instance in python from list as attributes

So I have an object:

class Particle(object):
    def __init__(self, x, y, vx, vy, ax, ay):
        self._x = int(x)
        self._y = int(y)
        self._vx = int(vx)
        self._vy = int(vy)
        self._ax = int(ax)
        self._ay = int(ay)
        # ...

I want to create an instance of that object from a list of numbers. How would I do that? Particle(list) doesn't work because it only inputs a list, not each value in the list. Thanks so much, I am sure there is a very obvious answer.

Upvotes: 2

Views: 150

Answers (2)

Vincent Savard
Vincent Savard

Reputation: 35927

Precede your list name by a star:

def foo(a, b, c):
    print(a, b, c)

a = [1,2,3]
foo(*a)
# 1 2 3

The star unpacks the list, which gives 3 separate values.

Upvotes: 3

Raymond Hettinger
Raymond Hettinger

Reputation: 226296

What you need is called "unpacking argument lists". Here's an example taken from the tutorial:

>>> range(3, 6)             # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args)            # call with arguments unpacked from a list
[3, 4, 5]

Upvotes: 2

Related Questions