我查看了SO上的无数'Python exec'线程,但找不到解决我的问题的线程。非常抱歉,如果这之前已经问过。这里是我的问题:为什么Python 3更改为exec会中断此代码?
# Python 2.6: prints 'it is working'
# Python 3.1.2: "NameError: global name 'a_func' is not defined"
class Testing(object):
def __init__(self):
exec("""def a_func():
print('it is working')""")
a_func()
Testing()
# Python 2.6: prints 'it is working'
# Python 3.1.2: prints 'it is working'
class Testing(object):
def __init__(self):
def a_func():
print('it is working')
a_func()
Testing()
作为标准功能定义在两个Python版本的作品,我假设的问题必须是一个变化的方式EXEC作品。我读了API文档的2.6和3 exec
和也可以参考“什么是新的Python 3.0”页面,看不出有任何理由代码将打破。
这似乎是很可能使任何人必须在5年内维持它的代码。 – Amber
我认为这是一个比实际使用的代码更包含的例子。我听说'exec'和'eval'在语言中占有一席之地。 –
@Amber也许我是个虐待狂? –