装饰器 decorator
类装饰器
class decorator(object):
def __init__(self, func):
self.func = func
def __call__(self, *args, **kw):
print 'input:', args, kw
return self.func(*args, **kw)
@decorator
def square_sum(*args, **kw):
sum = 0
for i in args:
sum += i**2
for j in kw.values():
sum += j**2
return sum
>>> square_sum(3, 4, key=5)
input: (3, 4) {'key': 5}
50
带参数的装饰器
def decorator(*args, **kw):
text = args
def _(func):
def wrapper(*args, **kw):
print 'text: %s' % text
print 'input:', args, kw
return func(*args, **kw)
return wrapper
return _
注意:decorator中的(*args, **kw) vs wrapper中的(*args, **kw)
举例(装饰器函数;装饰器类;有参与无参)
https://foofish.net/python-decorator.html
相比函数装饰器,类装饰器具有灵活度大、高内聚、封装性等优点。
class Foo(object):
def __init__(self, func):
self._fun = func
def __call__(self):
print ('class decorator running')
self._fun()
print ('class decorator ending')
@Foo
def bar():
print ('bar')
bar()
带参数的装饰器
def use_logging(level):
def decorator(func):
def wrapper(*args, **kwargs):
if level == "warn":
logging.warn("%s is running" % func.__name__)
elif level == "info":
logging.info("%s is running" % func.__name__)
return func(*args)
return wrapper
return decorator
@use_logging(level="warn")
def foo(name='foo'):
print("i am %s" % name)
foo()
检测Python程序执行效率及内存和CPU使用的7种方
http://python.jobbole.com/80754/
网友评论