小编Gre*_*war的帖子

使用Python 3中exec'ed字符串中定义的函数

为什么以下python3代码会产生错误?

a='''
def x():
  print(42)
'''

class Test:
    def __init__(self):
        exec(a)
        x()

t = Test()
Run Code Online (Sandbox Code Playgroud)

结果在此消息中:

Traceback (most recent call last):
  File "bug.py", line 11, in <module>
    t = Test()
  File "bug.py", line 9, in __init__
    x()
NameError: global name 'x' is not defined
Run Code Online (Sandbox Code Playgroud)

python python-3.x python-internals

20
推荐指数
3
解决办法
9197
查看次数

标签 统计

python ×1

python-3.x ×1

python-internals ×1