python 类装饰器,方法装饰器

一:装饰器介绍

  1. 为何要用装饰器 Python 中的装饰器是一种语法糖,可以在运行时,动态的给函数或类添加功能。 装饰器本质上是一个函数,使用 @ + 函数名就是可实现绑定给函数的第二个功能 。 将一些通用的、特定函数的功能抽象成一个装饰器,可以重复利用这些功能

  2. 什么是装饰器 “装饰”代指为被装饰对象添加新的功能,“器”代指器具/工具 装饰器的作用:就是在不修改被装饰对象源代码和调用方式的前提下为被装饰对象添加额外的功能。 装饰器使用场景:插入日志、性能测试、事务处理、缓存、权限校验 可以调用的有:函数、方法、类 函数装饰器分为:无参装饰器和有参装饰,二者都是使用都是需要【名称空间+函数嵌套+闭包+函数对象的组合知识】 使用“@”符号定义装饰器,前提是需要有一个函数作为工具然后被“@”装饰到其他函数头上,为这个函数添加功能

二:装饰器类,方法及有参数无参数方法

  1.类方法及带参数

class DecortorInterface(object):

    def __init__(self, apicode:str='', appkey:str=''):
        self.apicode = apicode
        self.appkey = appkey

    def __call__(self, func):
        def encryption(*args, **kwargs):
            result = func(*args, **kwargs)
            if isinstance(result, dict):
                result['apicode'] = self.apicode
                result['appkey'] = self.appkey
                print(result)
                return result
            else:
                print('类型返回异常')
                print(result)
                return result
        return encryption
@DecortorInterface(apicode="12",appkey="wa")
def add(types):
    print('我是add')
    return types
a= '{"q":1}'
add(a)
# 结果------------------
# 我是add
# 类型返回异常
# {"q":1}

    1.1.类方法中包含__init__,__call__内置方法(注意:类中如果想使用装饰器类型代码必须由__call__来做)

    解释:__call__()方法的作用其实是把一个类的实例化对象变成了可调用对象,也就是说把一个类的实例化对象变成了可调用对象,只要类里实现了__call__()方法就行。如当类里没有实现__call__()时,此时的对象p 只是个类的实例,不是一个可调用的对象,当调用它时会报错:‘Person’ object is not callable.__init__()初始化方法

  1.2.类方法不带参数

class Deco(object):
    def __call__(self, func):
        def new_func():
            print(f'[log] run function {func.__name__}')
            func()
        return new_func

@Deco()
def foo():
    print('in function foo')
foo()
# 结果
# [log] run function foo
# in function foo

  1.3.函数方法带参数

def deco(msg):
    def inner_deco(func):
        def new_func(*args, **kwargs):
            print(f'[log] run function {func.__name__}')
            rlt = func(*args, **kwargs)
            print(f'[log] {msg}')
            return rlt
        return new_func
    return inner_deco

@deco('some message')
def foo(a, b=None):
    print('in function foo')
    print(f'a is {a} & b is {b}')
    return 'ok'
rlt = foo('a')
# 结果
# [log] run function foo
# in function foo
# a is a & b is None
# [log] some message

  1.4.函数方法不带参数

def deco(func):
    def new_func():
        print(f'[log] run function {func.__name__}')
        func()
    return new_func

@deco
def foo():
    print('in function foo')
foo()
# 结果
# [log] run function foo
# in function foo

 

posted @ 2023-10-19 14:43  公子Learningcarer  阅读(164)  评论(0编辑  收藏  举报