【转载】 Python动态生成变量

用Python循环创建多个变量, 如创建 a1=   、a2=   、a3=   、a4=   、a5=    或  self.a1=    、self.a2=   、 self.a3=

一. 可以通过python的内置函数locals 来完成

locals是python的内置函数,他可以以字典的方式去访问局部和全局变量。
python里面用名字空间记录着变量,就像javascript的window一样,他记录着各种全局变量。
每个模块,每个函数都有自己的名字空间,记录着变量,常量,类的命名和值。

就像JS一样,当python在使用变量时,会按照下面的步骤去搜索:
1、函数或类的局部变量。
2、全局变量。
3、内置变量。
以上三个步骤,其中一下步骤找到对应的变量,就不会再往下找。如果在这三个步骤都找不到,就会抛出异常。

Python 也可以像javascript那样动态生成变量。我们看javascript的动态生成变量:

1 var obj = {};
2 for (var i =0, len = 10; i < len; i++){
3     obj['a' + i] = i;
4 }
5 
6 console.log(i); //{'a0':0, 'a1':1....,'a9':9}

Python中的locals 方法

1 createVar = locals()
2 listTemp = range(1,10)
3 for i,s in enumerate(listTemp):
4     createVar['a'+i] = s
5 print a1,a2,a3
6 #......
复制代码
1 def foo(args):
2     x=1
3     print locals()
4 
5 foo(123)
6 
7 #将会得到 {'arg':123,'x':1}
复制代码
1 for i in range(3):
2     locals()['a'+str(i)]=i
3     print 'a'+str(i)

打印结果:变量名:  a0  a1   a2   对应值  a0=0    a1=1    a2=2

二. 对于class,推荐使用setattr()方法

setattr给对象添加属性或者方法

setattr( object, name, value)

This is the counterpart of getattr(). The arguments
are an object, a string and an arbitrary value. The string may name an existing
attribute or a new attribute. The function assigns the value to the attribute,
provided the object allows it. For example, setattr(x,
'foobar', 123)
 is equivalent to
x.foobar = 123.

复制代码
1 class test(object) :
2     def __init__(self):
3         dic={'a':'aa','b':'bb'}
4         for i in dic.keys() :
5             setattr(self,i,dic[i]) #第一个参数是对象,这里的self其实就是test.第二个参数是变量名,第三个是变量值
6         print(self.a)
7         print(self.b)
8 t=test()
复制代码

打印结果: aa  ,   bb

 动态打印self变量:

1 exec("self.a"+str(i)+".move("+str(x)+","+str(y)+")")
2 exec("self.a"+str(i)+".show()")

提示: 动态创建字典会带来额外开销,如果可以的话,请尽量指定键值对。

猜你喜欢

转载自www.cnblogs.com/jfdwd/p/11129958.html