python exec问题:为什么不能连接'str'和'int'对象

goo*_*man 0 python exec

我在python 2.6和2.7下测试了这些.
See this is OK:
>>> exec'e = 1'
>>> exec'f = 2'
>>> exec'g = e + f'
>>> print g
3

But this returns error:
>>> cont = ['e = 1','f = 2','g = e + f']
>>> for e in cont:
... try:
... exec e
...除了Exception, em:
... print em
...
无法连接'str'和'int'对象

所以为什么?谢谢!

sen*_*rle 5

你选择的变量名很差.您使用的e同时作为for循环变量,并在int变量cont[0].发生的事情是第一次通过循环e == 'e=1'; 然后exec e被称为e == 1; 然后下一次通过循环,e == 'f=2'等等.通过最后的表达时间'g=e+f'exec编,e不再是一个整数,而是一个字符串-字符串'g=e+f'.