python学习之路6
装饰器:内嵌函数+高阶函数
一:函数调用顺序:其他高级语言类似,Python 不允许在函数未声明之前,对其进行引用或者调用
def bar(): print('in the bar') def foo(): print('in the foo') bar() foo()
错误示范
def foo(): print('in the foo') bar() foo()
def bar():
print('in the bar')
E:\python\python.exe E:/pyproject/1/装饰器.py in the foo Traceback (most recent call last): File "E:/pyproject/1/装饰器.py", line 9, in <module> foo() File "E:/pyproject/1/装饰器.py", line 7, in foo bar() NameError: name 'bar' is not defined
二:高阶函数
满足下列条件之一就可成函数为高阶函数
1、某一函数当做参数传入另一个函数中
2、函数的返回值包含n个函数,n>0
def bar(): print ('in the bar') def foo(func): res=func() return res foo(bar) #等同于bar=foo(bar)然后bar() in the bar
三:内嵌函数和变量作用域:
定义:在一个函数体内创建另外一个函数,这种函数就叫内嵌函数(基于python支持静态嵌套域)
函数嵌套示范:
def foo(): def bar(): print('in the bar') bar() foo() in the bar
局部作用域和全局作用域的访问顺序
x=0 def grandpa(): x=1 print(x) def dad(): x=2 print(x) def son(): x=3 print (x) son() dad() grandpa()
局部变量修改对全局变量的影响
y = 10 def test(): y = 2 print(y) test() print(y) 2 10
四:装饰器
装饰器:嵌套函数+高阶函数
调用方式:在原函数前面@装饰器函数名
示例:原函数test,调用方式test(),在不改变原函数以及不改变原函数调用的情况下新增计时功能。
import time def decorator(func): def wrapper(*args, **kwargs): start = time.time() func(*args, **kwargs) stop = time.time() print('run time is %s ' % (stop - start)) return wrapper @decorator #test=decorator(test)-->test=wrapper-->test()=wrappper() def test(list): for i in list: time.sleep(0.1) print('-' * 20, i) test(range(10)) E:\python\python.exe E:/pyproject/1/装饰器.py -------------------- 0 -------------------- 1 -------------------- 2 -------------------- 3 -------------------- 4 -------------------- 5 -------------------- 6 -------------------- 7 -------------------- 8 -------------------- 9 run time is 1.0073368549346924