[英]running python doc example has don't understand something in python scope and namespace chapter?
我正在學習python3.6文檔,當我查看python scopes and namespaces
,我嘗試運行此代碼,我發現在scope_test()
調用do_local()
打印結果與我的想法不同:
def scope_test():
def do_local():
spam = "local spam"
def do_nonlocal():
nonlocal spam
spam = "nonlocal spam"
def do_global():
global spam
spam = "global spam"
spam = "test spam"
do_local()
print("After local assignment:", spam)
do_nonlocal()
print("After nonlocal assignment:", spam)
do_global()
print("After global assignment:", spam)
scope_test()
print("In global scope:", spam)
我認為在調用do_local()
時應在do_local()
范圍內查找垃圾郵件,因為do_local()
范圍具有spam
變量,因此:
do_local()
print('After local assignment:', spam) # local spam
除非do_local()
沒有spam
變量,然后可以在scope_test()
找到spam
但是python解釋器的打印結果是:
do_local()
print('After local assignment:', spam) # test spam
與調用do_global()
時類似,我認為在此范圍內,因為global spam
是全局的,所以:
do_global()
print("After global assignment:", spam) # test spam
但是為什么結果是:
do_global()
print("After global assignment:", spam) # nonlocal spam
def scope_test():
def do_local():
spam = "local spam" #this spam variable is in do_local's scope
def do_nonlocal():
nonlocal spam #this spam variable refers to spam variable defined in outer function's ,that is scope_test's,scope
spam = "nonlocal spam"
def do_global():
global spam #this refers spam variable defined outside all functions (global)
spam = "global spam"
spam = "test spam" #this spam variable is defined in scope_test's scope
do_local()
print("After local assignment:", spam) #this spam var is still in scope_test's scope
do_nonlocal() #do_nonlocal is called and inside that spam variable (defined nonlocal) is changed which changes scope_test's spam
print("After nonlocal assignment:", spam) #this print is also in scop_test's scope but above function changed current scope's value
do_global() #changes spam var in global scope
print("After global assignment:", spam) #prints spam var in scop_test
scope_test() #execution starts
print("In global scope:", spam) #prints spam var in global scope as this print statement is in global scope
這是我運行程序后得到的結果。 讓我們經歷一下。
def do_local():
spam = "local spam"
將創建對象垃圾郵件,該垃圾郵件的范圍僅限於此函數do_local,並且在函數壽命到期時將其銷毀。 因此,在本地分配后,您會看到測試垃圾郵件的輸出,該輸出是使用spam = "test spam"
定義的,該spam = "test spam"
的范圍與函數scope_test有關。
def do_nonlocal():
nonlocal spam
spam = "nonlocal spam"
通過使用nonlocal關鍵字,您將告訴解釋器您正在使用的對象不限於功能do_nonlocal
的范圍。 因此,解釋器在此函數范圍之外搜索該對象,並在函數scope_test
找到它。 然后,它將與功能scope_test
的范圍相關的“非本地垃圾郵件”的值分配給該垃圾郵件對象。
def do_global():
global spam
spam = "global spam"
在這里,您實際上是在創建全局對象垃圾郵件,並為其分配“全局垃圾郵件”的值。 請記住:這是整個程序范圍的全局范圍。 但是,當您打印出垃圾郵件時,python會查找垃圾郵件對象並僅在函數范圍內找到它,例如,在do_nonlocal
函數調用中分配了“非本地垃圾郵件”值的垃圾郵件,因此您將非本地垃圾郵件視為輸出。
scope_test()
print("In global scope:", spam)
運行范圍測試后,最初包含“測試垃圾郵件”值的垃圾郵件對象的范圍在函數scope_test
結束后仍然存在。 因此,當您嘗試再次打印出垃圾郵件時,全局對象垃圾郵件將被打印出來,該垃圾郵件是您在do_global
中調用do_global
時test_scope
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.