一:函数调用顺序:其余高级语言相似,Python 不容许在函数未声明以前,对其进行引用或者调用python
def bar(): print('in the bar') def foo(): print('in the foo') bar() foo()
错误示范app
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
二:高阶函数函数
知足下列条件之一就可成函数为高阶函数spa
一、某一函数当作参数传入另外一个函数中code
二、函数的返回值包含n个函数,n>0blog
def bar(): print ('in the bar') def foo(func): res=func() return res foo(bar) #等同于bar=foo(bar)而后bar() in the bar
三:内嵌函数和变量做用域:作用域
定义:在一个函数体内建立另一个函数,这种函数就叫内嵌函数(基于python支持静态嵌套域)ast
函数嵌套示范:class
def foo(): def bar(): print('in the bar') bar() foo() in the bar
局部做用域和全局做用域的访问顺序test
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