• 装饰器带类参数 & 一个函数应用多个装饰器


    装饰器:不改变原函数的基础上,给函数增加功能的方式,称为装饰器 
    即:为已经存在的对象添加额外的功能
    装饰器其实就是一个闭包,把一个函数当做参数后返回一个替代版的函数

    decos.py:
    (装饰器的参数类)代码如下:
    class Locker1:
        def __init__(self):
            print('locker1...')
    
        @staticmethod
        def acquire():
            print('locker1 acquire...')
    
        @staticmethod
        def unlock():
            print('locker1 unlock...')
    

    class Locker2(Locker1): @staticmethod def acquire(): print('locker2 acquire...') @staticmethod def unlock(): print('locker2 unlock...')
     

    装饰器函数 和 主程序:

    # 装饰器函数:
    
    def locker_deco(cls):
        def _deco(func):
            def __deco(*args,**kwargs):
                print('before...')
                print(func.__name__)
                cls.acquire()
                try:
                    return func(*args,**kwargs)
                finally:
                    cls.unlock()
                print('after...')
            return __deco
        return _deco
    
    
    
    # 主程序:
    
    from decos import Locker1,Locker2
    
    class Example:
        @locker_deco(Locker1)
        def func1(self):
            print('func1...')
            return 5
    
        @locker_deco(Locker1)
        @locker_deco(Locker2)
        def func2(self,a,b):
            print('func2...')
            return a+b
    
    e=Example()
    e.func2(1,2)
    print('****')
    print(e.func2(1,2))


    运行结果:

    before...
    __deco
    locker1 acquire...
    before...
    func2
    locker2 acquire...
    func2...
    locker2 unlock...
    locker1 unlock...
    ****
    before...
    __deco
    locker1 acquire...
    before...
    func2
    locker2 acquire...
    func2...
    locker2 unlock...
    locker1 unlock...
    3
     
  • 相关阅读:
    vs2008打开aspx文件时设计界面死机情况的解决
    数据库设计知识点
    JS从样式表取值的函数currentStyle(IE),defaultView(FF)
    Iframe选区
    实用正则表达式(实用篇)
    46.class属性 Walker
    410.锚链接和空链接 Walker
    45.ID属性 Walker
    49.文件下载 Walker
    47.title和style属性 Walker
  • 原文地址:https://www.cnblogs.com/reyinever/p/10881574.html
Copyright © 2020-2023  润新知