类和函数是不同的,类内部的变量实际上是作为其属性分配给类的名称空间的,而在函数内部,变量只是不能在其外部访问的普通变量。
实际上,函数内部的局部变量是在首次解析该函数时确定的,并且python不会在全局范围内搜索它们,因为它知道您已将其声明为局部变量。
因此,一旦python看到
x = x + 1(赋值)并且没有
global为该变量声明,那么python将不会在全局或其他范围内寻找该变量。
>>> x = 'outer'>>> def func():... x = 'inner' #x is a local variable now... print x... >>> func()inner
常见陷阱:
>>> x = 'outer'>>> def func():... print x #this won't access the global `x`... x = 'inner' #`x` is a local variable... print x... >>> func()...UnboundLocalError: local variable 'x' referenced before assignment
但是,当您使用一条
global语句时,则使用python在
global范围内查找该变量。
阅读:当变量具有值时,为什么会收到UnboundLocalError?
nonlocal
:对于嵌套函数,您可以使用
nonlocalpy3.x中的语句修改在封闭函数中声明的变量。
但是类的工作方式不同,实际上
x在类内部声明的变量
A变为
A.x:
>>> x = 'outer'>>> class A:... x += 'inside' #use the value of global `x` to create a new attribute `A.x`... print x #prints `A.x`... outerinside>>> print xouter
您还可以直接从全局范围访问类属性:
>>> A.x'outerinside'
global在课堂上使用:
>>> x = 'outer'>>> class A:... global x... x += 'inner' #now x is not a class attribute, you just modified the global x... print x... outerinner>>> x'outerinner'>>> A.xAttributeError: class A has no attribute 'x'
函数的陷阱不会在类中引发错误:
>>> x = 'outer'>>> class A:... print x#fetch from globals or builitns... x = 'I am a class attribute' #declare a class attribute... print x#print class attribute, i.e `A.x`... outerI am a class attribute>>> x'outer'>>> A.x'I am a class attribute'
LEGB 规则:如果没有
global和
nonlocal被使用,则蟒蛇搜索顺序。
>>> outer = 'global'>>> def func(): enclosing = 'enclosing' def inner(): inner = 'inner' print inner#fetch from (L)ocal scope print enclosing #fetch from (E)nclosing scope print outer#fetch from (G)lobal scope print any #fetch from (B)uilt-ins inner()... >>> func()innerenclosingglobal<built-in function any>



