装饰器的应用场景
日志处理
- use_logging 不是代码逻辑函数,破坏代码结构;
def use_logging(func):
logging.warn("{0} is running".formart(func.__name__))
func()
def foo():
print("I am foo")
use_logging(foo)
- 函数进入和退出被称为横切面,面向切面编程;
- 还是不友好,不简化;
def use_logging(func):
def wrapper():
logging.warn("{0} is running ! ".format(func.__name__))
return func()
return wrapper
def foo():
print('i am foo')
foo = use_logging(foo)
foo()
def use_logging(func):
def wrapper():
logging.warn("{0} is running.".format(func.__name__))
return func()
return wrapper
@use_logging
def foo():
print("I am foo")
foo()
import logging
def use_logging(level): # 接收装饰器的参数
def decorator(func): # 返回函数
def wrapper(*args,**kwargs): ## 接收主函数的参数
if level == "warn": # 装饰器需要干的事情
logging.warning("{0} is running".format(func.__name__))
if level == "info":
logging.info("{0} is running...".format(func.__name__))
return func(*args)
return wrapper
return decorator
@use_logging(level = "warn")
def foo(name = 'foo'):
print(" i am {0}".format(name))
foo()
class Foo(object):
def __init__(self,func):
self._func = func
def __call__(self):
print('running...')
self._func()
print('ending...')
@Foo
def bar():
print('bar')
bar()