简体   繁体   English

Python - 使用列表创建新变量

[英]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.使用这种方法,构造函数的调用者可以使用 dict 或关键字 args 来传递名称和值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM