• Python装饰器


    什么是装饰器?

    • 在不改变原来代码的基础上,修改代码的逻辑
    • 本质就是一个高阶函数
    • 语法糖是@
    • 分类
      • 函数装饰器:定义一个函数当做装饰器
      • 类装饰器:定义一个类当做装饰器
    • 装饰器可以修饰普通方法,类方法,类...
    • 装饰器可以叠加使用

    函数装饰器

    • 装饰器本身不带参数
    def decorator(func):
        def _decorator(*args, **kwargs):
            print('decorator called, start!')
            ret = func(*args, **kwargs)
            print('decorator called, end!')
            return ret
        return _decorator
    
    @decorator
    def test(data):
        print('test : %s' % data)
    
    test('ok')
    • 装饰器本身带参数
    def decorator(*args, **kwargs):
        print(args[0])
        print(kwargs['one'])
        def _decorator(func):
            def __decorator(*args, **kwargs):
                print('decorator called, start!')
                ret = func(*args, **kwargs)
                print('decorator called, end!')
                return ret
            return __decorator
        return _decorator
    
    @decorator('x', one = 'a')
    def test(data):
        print('test : %s' % data)
    
    test('ok')

    类装饰器

    • 类装饰器本身不带参数
    class decorator:
        def __init__(self, func):
            self.func = func
    
        def __call__(self, *args, **kwargs):
            print('decorator called, start!')
            ret = self.func(*args, **kwargs)
            print('decorator called, end!')
            return ret
    
    @decorator
    def test(data):
        print('test : %s' % data)
    
    test('ok')
    • 类装饰器本身带参数
    class decorator:
        def __init__(self, x):
            self.x = x
    
        def __call__(self, func):
            print(self.x)
            def _dectorator(*args, **kwargs):
                print('decorator called, start!')
                ret = func(*args, **kwargs)
                print('decorator called, end!')
                return ret
            return _dectorator
    
    @decorator('a')
    def test(data):
        print('test : %s' % data)
    
    test('ok')
  • 相关阅读:
    (bfs入门)宝岛探险
    (bfs入门)走迷宫
    环形的处理P1880 [NOI1995]石子合并
    ZOJ2227Minimax三角划分
    UVA11400 Lighting System Design
    字符串匹配入门
    UVA12563 Jin Ge Jin Qu hao
    HDU1619 Unidirectional TSP
    ZOJ2581Tour
    UVA1025 A Spy in the Metro
  • 原文地址:https://www.cnblogs.com/chusiyong/p/11563190.html
Copyright © 2020-2023  润新知