python3 函数
返回函数
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
def func(flag): def sum(a,b): return a+b def jianfa(a,b): return a-b if flag == "+": return sum else: return jianfa result = func("+") print(result(1,2))
高阶函数
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
def caculate(num1,num2,func): result = func(num1,num2) print(result) def sum(a,b): return a + b def jianfa(a,b): return a - b caculate(6,2,sum)
匿名函数(lambda函数)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
s = [{"name":"zs","age":18},{"name":"zs2","age":19},{"name":"zs3","age":18.5}] # 按age的值排序 result = sorted(s, key=lambda x: x["age"]) # 按name的值排序 result2 = sorted(s, key=lambda x: x["name"]) print(result) print(result2) result3 = (lambda x,y : x+y)(1,2) print(result3)
闭包格式
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
def test(): a = 10 def test2(): print(a) return test2 # 等同于执行test函数里的test2函数 newd = test() newd()
闭包例子
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
def test(content,length): def test2(): print("-"*(length // 2) + content + "-"*(length // 2)) return test2 # 等同于执行test函数里的test2函数 newd = test("闭包",20) # 可以多次执用 newd() newd() # ----------闭包---------- # ----------闭包---------- # ----------xxx----------
闭包注意
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
def test(): num = 10 def test2(): # 加上这句才可以修改外部的num变量 # nonlocal num num = 666 print("test2",num) print(num) test2() print(num) return test2 newd = test() # 10 # test2 666 # 10
装饰器
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
def check(func): def inner(*args,**kwargs): print("登录验证") func(*args,**kwargs) return inner @check def fss(num1,num2,num3): print(num1,num2,num3) @check def fss2(num): print(num) fss(1,2,num3="aa") fss2("b")
带参数
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
def check(char): def getzsq(func): def inner(*args,**kwargs): print(char+"--","登录验证") func(*args,**kwargs) return inner return getzsq @check("*") def fss(num1,num2,num3): print(num1,num2,num3) @check("*") def fss2(num): print(num) fss(1,2,num3="aa") fss2("b")