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) #第一个参数是对象,这里的self其实就是test.第二个参数是变量名,第三个是变量值
6 print(self.a)
7 print(self.b)
8 t=test()
打印结果: aa , bb
动态打印self变量: