當我在不傳遞globals或locals參數的情況下調用execfile時,它會在目前命名空間中建立對象,但是如果我調用execfile并為globals(和/或locals)指定dict,它會在__builtin__命名空間中建立對象。
舉個例子:# exec.py
def myfunc():
print 'myfunc created in %s namespace' % __name__
exec.py是main.py中的execfile,如下所示。# main.py
print 'execfile in global namespace:'
execfile('exec.py')
myfunc()
print 'execfile in custom namespace:'
d = {}
execfile('exec.py', d)
d['myfunc']()
當我從指令行運作main.py時,得到以下輸出。execfile in global namespace:
myfunc created in __main__ namespace
execfile in custom namespace:
myfunc created in __builtin__ namespace
在第二種情況下,為什麼要在__builtin__命名空間中運作它?
此外,如果我試圖從__builtins__運作myfunc,就會得到一個AttributeError。(這是我希望發生的事情,但是為什麼__name__設定為__builtin__?)>>> __builtins__.myfunc()
Traceback (most recent call last):
File "", line 1, in ?
AttributeError: 'module' object has no attribute 'myfunc'
有人能解釋這種行為嗎?
謝謝