参考这几篇帖子:
https://stackoverflow.com/questions/11553721/using-a-string-variable-as-a-variable-name?answertab=active#tab-top
https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables
https://stackoverflow.com/questions/19122345/to-convert-string-to-variable-name
https://late.am/post/2012/04/30/the-exec-statement-and-a-python-mystery.html
和自己尝试,得出了以下几个方法时可用的。我主要是用了exec的方法,因为只是一个小脚本,而不是在类里面设置,我想在类里面,可以使用setattr的方法进行。
由于python 2 和 3的exec是不同的,所以实现的方法也略有差别。
python 3 :
exec 被当成一个函数 ,可以通过以下的方法来进行将字符串变成变量的名字进行赋值
x='buffalo' exec("%s = %d" % (x,2))
>>> foo = "bar" >>> exec(foo + " = 'something else'") >>> print bar something else
在python 2 当中,exec 是一个语句, 只能使用下面的方法:
x='buffalo' exec "%s = %d" % (x,2)
下面是我在mininet下面,用语句自动生成 主机,并且连接到某一个 交换机 上的示例:
host_pre = 's1h' ip_pre = '10.0.0.' ip_suff = '/24' for i in range(1,254): host_name = host_pre + str(i) ip_addr = ip_pre + str(i) + ip_suff exec "%s = self.addHost('%s' ,ip='%s')"% (host_name, \ host_name, ip_addr) exec "self.addLink(s1, %s)" % host_name