python 装饰器

1.在执行目标函数前附加一些内容或者功能:

def demo(func):
    print('before exec %s '%func.__name__)
    func()
    print('after exec %s '%func.__name__)
    return func
def func():
    print('hello world')

func = demo(func)
func()

2.使用语法糖@来装饰函数

def demo(func):
    print('before exec %s '%func.__name__)
    func()
    print('after exec %s '%func.__name__)
    return func
@demo
def func():
    print('hello world')
func()

3.使用内嵌包装饰函数保证每次新函数都被调用

def demo(func):
    def inner():
        print('before exec %s '%func.__name__)
        func()
        print('after exec %s '%func.__name__)
    return inner
@demo
def func():
    print('hello world')
func()

4.对带参数的函数进行装饰

def demo(func):
    def inner(a,b):
        print('before exec %s '%func.__name__)
        ret = func(a,b)
        print('after exec %s '%func.__name__)
        return ret
    return inner
@demo
def func(a,b):
    print('hello world')
    return a+b
print(func(1,2))

5.对参数数量不确定的函数进行装饰

def demo(func):
    def inner(*args,**kwargs):
        print('before exec %s '%func.__name__)
        ret = func(*args,**kwargs)
        print('after exec %s '%func.__name__)
        return ret
    return inner
@demo
def func(a,b):
    print('hello world func')
    return a+b
@demo
def func1(a,b,c):
    print('hello world func1')
    return a+b+c
print(func(1,2))
print(func1(1,2,3))

6.装饰器带参数

def demo(arg):
    def warper(func):
        def inner(*args,**kwargs):
            print('before exec %s %s'%(func.__name__,arg))
            ret = func(*args,**kwargs)
            print('after exec %s %s '%(func.__name__,arg))
            return ret
        return inner
    return warper
@demo('qq')
def func(a,b):
    print('hello world func')
    return a+b
@demo('wechat')
def func1(a,b,c):
    print('hello world func1')
    return a+b+c
print(func(1,2))
print(func1(1,2,3))

7.多个装饰器装饰一个函数

def wrapper1(func):
    def inner():
        print('wrapper1 ,before func')
        func()
        print('wrapper1 ,after func')
    return inner

def wrapper2(func):
    def inner():
        print('wrapper2 ,before func')
        func()
        print('wrapper2 ,after func')
    return inner

@wrapper2
@wrapper1
def f():
    print('in f')

f()

8.装饰器带类参数

'''''示例: 装饰器带类参数'''  
  
class locker:  
    def __init__(self):  
        print("locker.__init__() should be not called.")  
         
    @staticmethod  
    def acquire():  
        print("locker.acquire() called.(这是静态方法)")  
         
    @staticmethod  
    def release():  
        print("  locker.release() called.(不需要对象实例)")  
  
def deco(cls):  
    '''''cls 必须实现acquire和release静态方法'''  
    def _deco(func):  
        def __deco():  
            print("before %s called [%s]." % (func.__name__, cls))  
            cls.acquire()  
            try:  
                return func()  
            finally:  
                cls.release()  
        return __deco  
    return _deco  
 
@deco(locker)  
def myfunc():  
    print(" myfunc() called.")  
  
myfunc()  
myfunc()  

9.装饰器带类参数,并分拆公共类到其他py文件中,同时演示了对一个函数应用多个装饰器

class mylocker:  
    def __init__(self):  
        print("mylocker.__init__() called.")  
         
    @staticmethod  
    def acquire():  
        print("mylocker.acquire() called.")  
         
    @staticmethod  
    def unlock():  
        print("  mylocker.unlock() called.")  
  
class lockerex(mylocker):  
    @staticmethod  
    def acquire():  
        print("lockerex.acquire() called.")  
         
    @staticmethod  
    def unlock():  
        print("  lockerex.unlock() called.")  
  
def lockhelper(cls):  
    '''''cls 必须实现acquire和release静态方法'''  
    def _deco(func):  
        def __deco(*args, **kwargs):  
            print("before %s called." % func.__name__)  
            cls.acquire()  
            try:  
                return func(*args, **kwargs)  
            finally:  
                cls.unlock()  
        return __deco  
    return _deco  

  

'''''装饰器带类参数,并分拆公共类到其他py文件中 
同时演示了对一个函数应用多个装饰器'''  
  
from mylocker import *  
  
class example:  
    @lockhelper(mylocker)  
    def myfunc(self):  
        print(" myfunc() called.")  
 
    @lockhelper(mylocker)  
    @lockhelper(lockerex)  
    def myfunc2(self, a, b):  
        print(" myfunc2() called.")  
        return a + b  
  
if __name__=="__main__":  
    a = example()  
    a.myfunc()  
    print(a.myfunc())  
    print(a.myfunc2(1, 2))  
    print(a.myfunc2(3, 4))  

  

posted @ 2018-04-20 14:10  大叔曹  阅读(215)  评论(0编辑  收藏  举报