匿名函数:
calc=lambda x:x*3 print(calc(3)) #返回9
高阶函数:
- 可以把一个函数名当做实参传给另一个函数
-
import time def bar(): print("in bar") def test(func): print(func) func() test(bar) #执行结果: #<function bar at 0x000000C7B80B3E18> ---bar这个函数的内存地址 #in bar
- 返回值中可以包含函数名
-
def bar(): print("in bar") def test(func): print("in test") return func bar=test(bar) bar() #执行结果in test in bar
- 函数就是变量
-
def bar(): print("in bar") test1=bar test1() #执行结果: in bar
嵌套函数
def foo(): print("in foo") def bar(): #有局部变量的特性, 只能在函数内部调用 print("in bar") bar() foo() #执行结果:in foo in bar
装饰器:
本质是函数, 功能是为其他函数添加附加功能
- 不能修改被装饰函数的源代码
- 不能修改被装饰憾事的调用方式
装饰器示例1: 统计函数的运行时间
实现原理: 将test这个函数传给timeer, 再将返回值函数赋值给test, 执行test, 即执行wrapper()
弊端: 加了装饰器之后, 返回值会get不到
import time def timmer(func): def wrapper(*args,**kwargs): start_time=time.time() func() stop_time=time.time() print("run time:",stop_time-start_time) return wrapper @timmer def test(): time.sleep(3) print("i am in test") test()
执行结果:
i am in test
run time: 3.0001983642578125
装饰器示例2: 实现登录拦截的功能
def auth(func): #先将home传给auth, 再将wrapper赋值给home, 执行home, 即执行wrapper def wrapper(*args,**kwargs): username=input("username:").strip() #先要求输入用户名密码 pwd=input("pwd:").strip() if username=="alex" and pwd=="123456": #验证通过打印pass print("pass") func(*args,**kwargs) # res=func(*args,**kwargs) # return res else: exit("验证失败!") #验证不通过程序退出 return wrapper def index(): print("欢迎进入登录页!") @auth def home(name): print("欢迎{name}进入首页!".format(name=name)) index() home("bell")
装饰器示例3: 装饰器传入参数
def auth(auth_type): def outer_wrapper(func): def wrapper(*args, **kwargs): if auth_type=="local": user_name=input("username:").strip() if user_name=="alex": print("pass") func(*args, **kwargs) else: exit() elif auth_type=="ldap": print("ldap") func(*args, **kwargs) return wrapper return outer_wrapper @auth(auth_type="local") def home(): print("home!") @auth(auth_type="ldap") def bbs(): print("bbs!") home() bbs()