类和函数不同,类内部的变量实际上被分配到类的命名空间作为其属性,而函数内部的变量只是普通变量,无法在其外部访问。
函数内部的局部变量实际上是在函数第一次解析时决定的,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 for 在中查找该变量global
scope.
Read: 当变量有值时,为什么我会收到 UnboundLocalError? http://docs.python.org/2/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value
nonlocal
:对于嵌套函数,您可以使用nonlocal
py3.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 x
outer
您还可以直接从全局范围访问类属性:
>>> A.x
'outerinside'
Using 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.x
AttributeError: 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`
...
outer
I am a class attribute
>>> x
'outer'
>>> A.x
'I am a class attribute'
LEGB规则:如果没有global
and nonlocal
使用然后 python 按此顺序搜索。
>>> 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()
inner
enclosing
global
<built-in function any>