在Python中,装饰器和迭代器、生成器都是非常重要的高级函数。
在讲装饰器之前,我们先要学习以下三个内容:
一、函数的作用域
1、作用域介绍
Python中的作用域分为四种情况:
- L:local,局部作用域,即函数中定义的变量;
- E:enclosing,嵌套的父级函数的局部作用域,即包含此函数的上级函数的局部作用域,但不是全局的;
- G:globa,全局变量,就是模块级别定义的变量;
- B:built-in,系统固定模块里面的变量,比如int, bytearray等。
搜索变量的优先级顺序依次是:L –> E –> G –>B,即:局部作用域>外层作用域>当前模块中的全局>Python内置作用域。
1 x = int(2.9) # int built-in 2 3 g_count = 0 # global 4 5 def outer(): 6 o_count = 1 # enclosing 7 def inner(): 8 i_count = 2 # local 9 print(o_count) 10 print(i_count) # 找不到 11 inner() 12 outer() 13 14 print(o_count) #找不到
当然,local和enclosing是相对的,enclosing变量相对上层来说也是local。
2、作用域的产生
在Python中,只有函数(def、lambda)、类(class)以及模块(module)才会引入新的作用域,其它的代码块(如if、try、for等)是不会引入新的作用域的,如下代码:
1 if 2>1: 2 x = 1 3 print(x) # 1
if并没有引入一个新的作用域,x仍处在当前作用域中,后面代码可以使用。
1 def test(): 2 x = 2 3 print(x) # NameError: name 'x2' is not defined
上面这段代码则会报错,因为def、class、lambda是可以引入新作用域的。
3、变量的修改
1 x = 6 2 def f(): 3 print(x) 4 x = 5 5 f() 6 7 # 错误的原因在于print(x)时,解释器会在局部作用域找,会找到x=5(函数已经加载到内存),但x使用在声明前了,所以报错: 8 # local variable 'x' referenced before assignment.如何证明找到了x=5呢?简单:注释掉x=5,x=6,报错为:name 'x' is not defined 9 10 # 同理 11 x = 6 12 def f(): 13 x += 1 # local variable 'x' referenced before assignment. 14 f()
4、global关键字
当内部作用域想修改外部作用域的变量时,就要用到global和nonlocal关键字了,当修改的变量是在全局作用域(global作用域)上的,就要使用global先声明一下,代码如下:
1 count = 10 2 def outer(): 3 global count 4 print(count) #10 5 count = 100 6 print(count) #100 7 outer() 8 print(count) #100
5、nonlocal关键字
global关键字声明的变量必须在全局作用域上,不能嵌套作用域上,当要修改嵌套作用域(enclosing作用域,外层非全局作用域)中的变量怎么办呢,这时就需要nonlocal关键字了,代码如下:
1 def outer(): 2 count = 10 3 def inner(): 4 nonlocal count 5 count = 20 6 print(count) #20 7 inner() 8 print(count) #20 9 outer()
6、作用域小结
- 变量查找顺序:LEGB,作用域局部>外层作用域>当前模块中的全局>python内置作用域;
- 只有函数、类以及模块才能引入新的作用域;
- 对于一个变量,内部作用域先声明就会覆盖外部变量,不声明直接使用,就会使用外部作用域的变量;
- 内部作用域要修改外部作用域变量的值时,全局变量要使用global关键字,嵌套作用域变量要使用nonlocal关键字。nonlocal是python3新增的关键字,有了这个 关键字,就能完美的实现闭包了;
二、函数即对象
在Python中,函数和之前学过的字符串、整型、列表等一样都是对象,而且函数是最高级的对象(对象是类的实例化,可以调用相应的方法,函数是包含变量的对象)。如下:
1 def foo(): 2 print('i am the foo') 3 bar() 4 5 def bar(): 6 print('i am the bar') 7 8 foo()
接着,我们再聊一下函数在内存的存储情况:
函数对象的调用仅仅比其它对象多了一个()而已!foo,bar与a,b一样都是个变量名。
既然函数是对象,那么自然满足下面两个条件:
1、函数可以被赋值给其他变量
1 def foo(): 2 print('foo') 3 bar=foo 4 bar() 5 foo() 6 print(id(foo),id(bar)) #1386464801520 1386464801520
2、函数可以被定义在另外一个函数内(作为参数或者返回值),类似于整型、字符串等对象
1 # *******函数名作为参数********** 2 def foo(func): 3 print('foo') 4 func() 5 6 def bar(): 7 print('bar') 8 9 foo(bar) 10 11 # *******函数名作为返回值********* 12 def foo(): 13 print('foo') 14 return bar 15 16 def bar(): 17 print('bar') 18 19 b = foo() 20 b()
三、函数的嵌套及闭包