python3 exec()在函数调用中没有按预期工作

时间:2018-02-27 22:38:21

标签: python-3.x function-calls

code1.py

if(__name__=="__main__"):
    var = "first_name"
    inp = "hello"
    exec("%s = '%s'" % (var,inp))
    print(first_name)

code2.py

def func():
    var = "first_name"
    inp = "hello"
    exec("%s = '%s'" % (var,inp))
    print(first_name)

if(__name__=="__main__"):
    func()

给出两个是两个不同的代码 code1.py按预期工作。 code2.py显示错误

Traceback (most recent call last):
  File "bad.py", line 8, in <module>
    func()
  File "bad.py", line 5, in func
    print(first_name)
NameError: name 'first_name' is not defined

有人可以解释为什么会这样吗?

0 个答案:

没有答案