开发者

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?


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


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}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜