python3函数中的作用域函数?
当我在阅读python中的名称空间和作用域时,我读到了python3函数中的作用域函数?,python,scope,Python,Scope,当我在阅读python中的名称空间和作用域时,我读到了 -the innermost scope, which is searched first, contains the local names -the scopes of any enclosing functions, which are searched starting with the nearest enclosing scope, contains non-local, but also non-global names -t
-the innermost scope, which is searched first, contains the local names
-the scopes of any enclosing functions, which are searched starting with the nearest enclosing scope, contains non-local, but also non-global names
-the next-to-last scope contains the current module’s global names
-the outermost scope (searched last) is the namespace containing built-in names
但当我试着这样做时:
def test() :
name = 'karim'
def tata() :
print(name)
name='zaka'
print(name)
tata()
我已收到此错误:
UnboundLocalError: local variable 'name' referenced before assignment
当语句print(name)时,tata()函数将在当前作用域中找不到name,因此python将在作用域中上升并在test()中找到它函数作用域号???在Python3中,您可以使用
非本地名称
告诉python,名称
未在本地作用域中定义,它应该在外部作用域中查找
这项工作:
def tata():
nonlocal name
print(name)
name='zaka'
print(name)