【发布时间】:2011-09-27 12:52:46
【问题描述】:
我查看了 SO 上的无数“Python 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 工作方式的更改。我阅读了 exec 的 2.6 和 3 的 API 文档,还阅读了“Python 3.0 中的新功能”页面,但看不出代码会中断的任何原因。
【问题讨论】:
-
这似乎是很可能让必须在 5 年内维护它的人哭泣的代码。
-
我认为这更像是一个包含的示例,而不是代码的实际使用。我听说
exec和eval在语言中占有一席之地。
标签: python python-3.x metaprogramming exec backwards-compatibility