2 回答

TA貢獻1777條經驗 獲得超10個贊
從文檔中:
如果提供的話,局部變量可以是任何映射對象。請記住,在模塊級別,全局變量和局部變量是相同的字典。如果 exec 獲取兩個單獨的對象作為全局對象和局部對象,則代碼將像嵌入在類定義中一樣執行。
并且類定義不會創建封閉范圍,請注意,這就是為什么您不能在不使用 的情況下從另一個方法調用方法self
。所以只要把字典傳過去就可以了globals()
?;蛘邔蓚€相同的字典傳遞給兩個參數。
In [4]: def run_code():
? ?...:? ? ?code = """
? ?...: def foo():
? ?...:? ?print('foo')
? ?...:? ?return 1
? ?...:
? ?...: def bar():
? ?...:? ?print('bar calls foo')
? ?...:? ?return 1 + foo()
? ?...:
? ?...: result = bar()
? ?...: """
? ?...:? ? ?namespace = {}
? ?...:? ? ?exec(code, namespace)
? ?...:? ? ?print('Result: {}'.format(namespace['result']))
? ?...:
In [5]: run_code()
bar calls foo
foo
Result: 2

TA貢獻1798條經驗 獲得超7個贊
code = """
def foo():
print('foo')
return 1
def bar():
global foo;
print('bar calls foo')
return 1 + foo()
result = bar()
"""
def run_code():
exec(code, globals(), locals())
print('Result: {}'.format(locals()['result']))
run_code()
輸出:
bar calls foo
foo
Result: 2
添加回答
舉報