python 装饰器
很久没有怎么用装饰器了,重新温习了一下装饰器的使用,直接上代码:
#coding=utf-8
def logging(level):
def wrapper(func):
def inner_wrapper(*args, **kwargs):
print("[{level}]: enter function {func}()".format(
level=level,
func=func.__name__))
return func(*args, **kwargs)
return inner_wrapper
return wrapper
@logging(level='INFO')
def say(something):
print("say {}!".format(something))
# 如果没有使用@语法,等同于
# say = logging(level='INFO')(say)
@logging(level='DEBUG')
def do(something):
print("do {}...".format(something))
if __name__ == '__main__':
say('hello')
do("my work")
运行结果如下:
F:\dev\python\python.exe F:/pyCharm/pratice/decorate_demo/demo_3.py
[INFO]: enter function say()
say hello!
[DEBUG]: enter function do()
do my work...
Process finished with exit code 0
class logging(object):
def __init__(self, level='INFO'):
self.level = level
def __call__(self, func): # 接受函数
def wrapper(*args, **kwargs):
print("[{level}]: enter function {func}()".format(
level=self.level,
func=func.__name__))
func(*args, **kwargs)
return wrapper # 返回函数
@logging(level='INFO')
def say(something):
print("say {}!".format(something))
if __name__=="__main__":
say("abccc")
运行结果如下:
F:\dev\python\python.exe F:/pyCharm/pratice/decorate_demo/class_demo.py
[INFO]: enter function say()
say abccc!
Process finished with exit code 0