1. 普通装饰器
import logging
1. foo = use_loggine(foo)
def use_loggine(func):
def wrapper():
logging.warn("%s is running " % func.__name__)
return func()
return wrapper
@use_loggine
def foo():
print "aaa"
foo()
print foo.__name__
2. func 需要参数:
foo = use_loggine(foo) 第一个参数就是func这个函数对象,不包含参数foo(params)
def use_loggine(func):
def wrapper(name):
logging.warn("%s is running " % func.__name__)
return func(name)
return wrapper
@use_loggine
def foo(name):
print "name is %s" % name
3. 装饰器带参数
foo = use_logging('warn')(foo) 还是把被装饰的函数当做参数赋给装饰器
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.warn("%s is running" % func.__name__)
return func(*args)
return wrapper
return decorator
@use_logging('warn')
def foo(name):
print "i am %s" % name
foo = use_logging('warn')(foo)
print foo.__name__
foo('foo')
4. 类装饰器,还是把被装饰的函数当做参数赋给装饰器
foo = Foo(params)(func)
class Foo(object):
def __init__(self, name):
self.name = name
def __call__(self, func):
def aa():
print "class decorator running"
print "name is :%s" % self.name
func()
print 'class decorator ending'
return aa
@Foo("hello")
def bar():
print "world"
bar()
@deco
def foo()
pass
foo = deco(foo)
@deco(xx)
def foo():
pass
foo = deco(xx)(foo)
5. 类方法装饰器
类方法装饰器和其他装饰器没有什么区别,只不过在装饰器内部返回的函数中,第一个参数是固定的,是调用方法的对象本身,如
果是实例对象,就是self,是类方法的话,就是cls,静态方法的话,没有第一个参数。
from functools import wraps
def method_decor(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
u = func(*args, **kwargs)
return u
except Exception as e:
args[0].bb() # args[0]就是self或者cls。可以在args前面定义self,更加方便u = func(self,*args, **kwargs)
return 'an Exception raised.'
return wrapper
class Foo(object):
@method_decor
def aa(self):
# print("This is wraped method")
raise Exception('aa')
def bb(self):
print("This is called method")
a = Foo()
a.aa()
以上这篇python装饰器相当于函数的调用方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。