作者:手机用户2602938483 | 来源:互联网 | 2023-10-12 15:26
篇首语:本文由编程笔记#小编为大家整理,主要介绍了python3 函数相关的知识,希望对你有一定的参考价值。
返回函数
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))
View Code 高阶函数
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)
View Code匿名函数(lambda函数)
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)
View Code 闭包格式
def test():
a = 10
def test2():
print(a)
return test2
# 等同于执行test函数里的test2函数
newd = test()
newd()
View Code 闭包例子
def test(content,length):
def test2():
print("-"*(length // 2) + content + "-"*(length // 2))
return test2
# 等同于执行test函数里的test2函数
newd = test("闭包",20)
# 可以多次执用
newd()
newd()
# ----------闭包----------
# ----------闭包----------
# ----------xxx----------
View Code 闭包注意
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
View Code
装饰器
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")
View Code 带参数
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")
View Code