Zvi
Zvi

Reputation: 207

Python - Create new variables using list

I would like to create new variables from a list.

For example:

mylist=[A,B,C]

From which i would like to create the following variables:

self.varA
self.varB
self.varC

How can create these new variables in a loop?

Upvotes: 2

Views: 5085

Answers (2)

John Machin
John Machin

Reputation: 82934

Your question ignores the fact that the variables need values ... who is going to supply what values how? Here is a solution to one of the possible clarified questions:

With this approach, the caller of your constructor can use either a dict or keyword args to pass in the names and values.

>>> class X(object):
...     def __init__(self, **kwargs):
...         for k in kwargs:
...             setattr(self, k, kwargs[k])
...

# using a dict

>>> kandv = dict([('foo', 'bar'), ('magic', 42), ('nix', None)])
>>> print X(**kandv).__dict__
{'nix': None, 'foo': 'bar', 'magic': 42}

# using keyword args

>>> print X(foo='bar', magic=42, nix=None).__dict__
{'nix': None, 'foo': 'bar', 'magic': 42}

Upvotes: 0

Dan D.
Dan D.

Reputation: 74655

mylist=['A','B','C']
for name in mylist:
    setattr(self, name, None)

but this is nearly always a bad idea and the values should be in a dict like:

self.v = {}
for name in mylist:
    self.v[name] = None

Upvotes: 6

Related Questions