重生之篮球战场指挥家,长途汽车票查询时刻表 票价,ca1867
装饰器本质也是一个函数, 只不过这个函数需要遵循以下规则:
(*args, **kwargs):
以满足所有函数需要
之后通过@语法糖即可装饰到任意函数上
# 不带参数的装饰器 def pre_do_sth(func): def wrapper(*args, **kwargs): print("do sth before call one") func(*args, **kwargs) return wrapper @pre_do_sth def echo(msg): print(msg) echo("hello world")
do sth before call one hello world
实际上调用的是 wrapper("hello world") --> echo("hello world")
只需要写一个返回 装饰器(入参只有一个, 返回值是一个函数)函数的函数
同样也能利用@语法糖
# 带参数的装饰器 def pre_do_sth_2(msg): def decorator(func): def wrapper(*args, **kwargs): print("do sth before call two, print:%s"%(msg)) func(*args, **kwargs) return wrapper return decorator @pre_do_sth_2("foo") def echo(msg): print(msg) echo("hello world")
实际上@后面并不是对pre_do_sth_2这个函数生效 而是对pre_do_sth_2的返回值生效
do sth before call two, print:foo hello world
先声明的装饰器先执行, 即在最外层
# 不带参数的装饰器 def pre_do_sth(func): def wrapper(*args, **kwargs): print("do sth before call one") func(*args, **kwargs) return wrapper # 带参数的装饰器 def pre_do_sth_2(msg): def decorator(func): def wrapper(*args, **kwargs): print("do sth before call two, print:%s"%(msg)) func(*args, **kwargs) return wrapper return decorator @pre_do_sth @pre_do_sth_2("foo") def echo(msg): print(msg) echo("hello world")
do sth before call one do sth before call two, print:foo hello world
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
新手学习Python2和Python3中print不同的用法
Python基于os.environ从windows获取环境变量
网友评论