37,719
社区成员
发帖
与我相关
我的任务
分享
a = compile('''
def f1():
print 'hello', d
def f2():
print 'hello world'
''', 'test', 'exec')
exec(a)
f1()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "test", line 3, in f1
NameError: global name 'd' is not defined
my_code = '''
def f1():
print 'hello'
def f2():
print 'hello world'
'''
a = compile(my_code, 'test', 'exec')
#将编译后的代码对象执行
exec(a)
#此时, my_code中的那些方法什么的就相当于做了一次模块导入. 进入了当前的名称空间.
#因此, 可以直接使用
f1()
f2()