美文网首页
python decorator

python decorator

作者: 白菜的白v | 来源:发表于2019-04-03 22:48 被阅读0次

实现一个log的decorator,使它既支持:

@log
def f():
    pass

也支持:

@log("ERROR")
def f():
    pass

实现:

from functools import wraps

def log(ft):
    if isinstance(ft, str):
        level = ft
        def wrapper(func):
            @wraps(func)
            def inner_wrapper(*args, **kwargs):
                print("Log[%s]: call %s()" % (level, func.__name__))
                c = func(*args, **kwargs)
                print("Log[%s]: end call %s()" % (level, func.__name__))
                return c
            return inner_wrapper
        return wrapper
    else:
        level = "INFO"
        @wraps(ft)
        def wrapper(*args, **kwargs):
            print("Log[%s]: call %s()" % (level, ft.__name__))
            c = ft(*args, **kwargs)
            print("Log[%s]: end call %s()" % (level, ft.__name__))
            return c
        return wrapper

使用log 装饰器装饰方法:

@log
def my_sum(*args):
    return sum(*args)

@log("ERROR")
def just_print():
    """just print Hello World string"""
    print("Hello World")

n = my_sum(range(0, 10))
print(n)
just_print()

输出:

Log[INFO]: call my_sum()
Log[INFO]: end call my_sum()
45
Log[ERROR]: call just_print()
Hello World
Log[ERROR]: end call just_print()

@wraps()的作用

functools.wraps 则可以将原函数对象的指定属性复制给包装函数对象, 默认有 _module_、_name_, _doc_
如果打印just_print._name_和 just_print._doc_

print(just_print.__name__)
print(just_print.__doc__)

输出:

just_print
just print Hello World string

如果我们把log装饰器函数里的@wraps()注释删掉,那么则输出:

inner_wrapper
None

相关文章

  • python常用的装饰器

    Python中有很多装饰器(decorator),可以减少冗余代码。Decorator本质上也是函数,只是它的参数...

  • Python中的Decorator装饰器

    Decorator 装饰器 理解decorator(装饰器)的关键, 在于理解在python中函数是第一公民, 并...

  • Python Decorator

    利用装饰器记录函数运行时间 list去空s=['A', '', 'B', None, 'C', ' ']s=...

  • Python Decorator

    flask中有很多装饰器,今天来整理下Python中装饰器的相关概念。 1. 最简单的装饰器 我们常常可以看到类似...

  • Decorator in Python

    First look at what a decorator code really is doing.The f...

  • Python decorator

    话说昨天面试python开发的时候,做了一个笔试题。 本来以为自己还算有python开发经验的,但是一真正测试才发...

  • 【Python】decorator

    decorator @ 装饰器本质上是一个Python函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外...

  • python decorator

    实现一个log的decorator,使它既支持: 也支持: 实现: 使用log 装饰器装饰方法: 输出: @wra...

  • TypeError: 'NoneType' object is

    Python在使用decorator时,报错TypeError: 'NoneType' object is not...

  • JavaScript装饰器 Decorator

    前言 许多面向对象都有decorator(装饰器)函数,比如python中也可以用decorator函数来强化代码...

网友评论

      本文标题:python decorator

      本文链接:https://www.haomeiwen.com/subject/qfntiqtx.html