编程语言
首页 > 编程语言> > Python 之 装饰器及文档字符串 随性笔记

Python 之 装饰器及文档字符串 随性笔记

作者:互联网

Python 之 装饰器及文档字符串 随性笔记

1、装饰器

2、文档字符串

def add(x, y):
    """
    This is a function of addition.
    """
    return x + y

print("name = {}\ndoc = {}".format(add.__name__, add.__doc__, add.__defaults__))
print('=' * 55)
print(help(add))

name = add
doc = 
    This is a function of addition.
    
=======================================================
Help on function add in module __main__:

add(x, y)
    This is a function of addition.

None

3、装饰器执行过程

3.1 请浏览以下代码

print('add1 >>>', add1(1, 2))
print('add2 >>>', add2(1, 2, 3))
# 上述代码执行结果
=== wrapper start ===
add1 fn_id is 121600328
=== wrapper end ===
add1 3
=== wrapper start ===
add2 fn_id is 121601048
Too slow.
=== wrapper end ===
add2 6

3.2 结合以下问题进行思考

4、装饰器函数的版本迭代改进

4.1 第一版,函数属性会被替换

import datetime
import time

def logger(fn):
    def wrapper(*args, **kwargs):
        """I am wrapper."""
        start = datetime.datetime.now()
        ret = fn(*args, **kwargs)
        duration = datetime.datetime.now() - start
        print('function {} took {}s.'.format(fn.__name__, duration.total_seconds()))
        return ret
    return wrapper

@logger   # 相当于 add = logger(add)
def add(x,y):
    """I am add."""
    time.sleep(2)
    return x + y

print(add(5, y = 8))
print(add.__name__, add.__doc__)
function add took 2.0s.
13
wrapper I am wrapper.

4.2 第二版,构造函数还原函数属性

import datetime
import time

def copy_properties(src, dst):
    dst.__name__ = src.__name__
    dst.__doc__ = src.__doc__

def logger(fn):
    def wrapper(*args, **kwargs):
        """I am wrapper."""
        start = datetime.datetime.now()
        ret = fn(*args, **kwargs)
        duration = datetime.datetime.now() - start
        print('function {} took {}s.'.format(fn.__name__, duration.total_seconds()))
        copy_properties(fn, wrapper)
        return ret
    return wrapper

@logger   # 相当于 add = logger(add)
def add(x,y):
    """I am add."""
    time.sleep(2)
    return x + y
              
print(add(5, y = 8))
print(add.__name__, '|||', add.__doc__)
function add took 2.0s.
13
add ||| I am add.

4.3 第三版,柯里化新建函数

import datetime
import time

# 柯里化
def copy_properties(src):
    def _copy_properties(dst):
        dst.__name__ = src.__name__
        dst.__doc__ = src.__doc__
        return dst
    return _copy_properties

def logger(fn):
    def wrapper(*args, **kwargs):
        """I am wrapper."""
        start = datetime.datetime.now()
        ret = fn(*args, **kwargs)
        duration = datetime.datetime.now() - start
        print('function {} took {}s.'.format(fn.__name__, duration.total_seconds()))
        # copy_properties(fn)(wrapper) => _copy_properties(wrapper)
        copy_properties(fn)(wrapper)
        return ret
    return wrapper

@logger   # 相当于 add = logger(add)
def add(x,y):
    """I am add."""
    time.sleep(2)
    return x + y
              
print(add(5, y = 8))
print(add.__name__, '|||', add.__doc__)
function add took 2.0s.
13
add ||| I am add.

4.4 第四版,改造成装饰器

import datetime
import time

def copy_properties(src):
    def _copy_properties(dst):
        dst.__name__ = src.__name__
        dst.__doc__ = src.__doc__
        return dst
    return _copy_properties

def logger(fn):
    @copy_properties(fn) 
    # 带参装饰器
    # wrapper => copy_properties(fn)(wrapper) => _copy_properties(wrapper)
    def wrapper(*args, **kwargs):
        """I am wrapper."""
        start = datetime.datetime.now()
        ret = fn(*args, **kwargs)
        duration = datetime.datetime.now() - start
        print('function {} took {}s.'.format(fn.__name__, duration.total_seconds()))
        # copy_properties(fn)( wrapper)
        return ret
    return wrapper

@logger   
# 相当于 add = logger(add) => add = wrapper
# 无参装饰器,本质上等效为 单参数 的函数
def add(x,y):  # lambda x, y:x + y
    """I am add."""
    print('===== call add =====')
    time.sleep(2)
    return x + y
              
print(add(5, y = 8))
print(add.__name__, '|||', add.__doc__)
===== call add =====
function add took 2.0s.
13
add ||| I am add.

4.5 第五版,使用 functools

from functools import update_wrapper, wraps
import datetime
import time

def logger(fn):
    @wraps(fn)
    def wrapper(*args, **kwargs):
        """I am wrapper."""
        start = datetime.datetime.now()
        ret = fn(*args, **kwargs)
        duration = datetime.datetime.now() - start
        print('function {} took {}s.'.format(fn.__name__, duration.total_seconds()))
        return ret
    return wrapper

@logger   
def add(x,y):
    """I am add."""
    time.sleep(2)
    return x + y
              
print(add(5, y = 8))
print(add.__name__, '|||', add.__doc__)
function add took 2.0s.
13
add ||| I am add.

4.6 第六版,增加函数执行时间判断

from functools import update_wrapper, wraps
import datetime
import time


def logger(duration=5):
    def _logger(fn):
        @wraps(fn)  
        def wrapper(*args, **kwargs):
            """I am wrapper."""
            start = datetime.datetime.now()
            ret = fn(*args, **kwargs)
            delta = (datetime.datetime.now() - start).total_seconds()
            if delta > duration:
                print('function {} took {:.2f}s.'.format(fn.__name__, delta))
            else:
                print('function {} run so fast.'.format(fn.__name__))
            return ret
        return wrapper
    return _logger

@logger(3) 
def add(x,y):
    """I am add."""
    time.sleep(2)
    return x + y
              
print(add(5, y = 8))
print(add.__name__, '|||', add.__doc__)
function add run so fast.
13
add ||| I am add.

4.7 第七版,把之前函数进行抽象

from functools import update_wrapper, wraps
import datetime
import time

def x(delta, func, duration):
    if delta > duration:
        print('function {} took {:.2f}s. It run too slow.'.format(func.__name__, delta))
    
def logger(duration=2, func=x):
    def _logger(fn):
        @wraps(fn)  # wrapper = update_wrapper(fn)(wrapper)
        def wrapper(*args, **kwargs):
            start = datetime.datetime.now()
            ret = fn(*args, **kwargs)
            delta = (datetime.datetime.now() - start).total_seconds()
            func(delta, fn, duration)
            return ret
        return wrapper
    return _logger

@logger()   
def add(x,y):  
    time.sleep(3)
    return x + y
              
print(add(5, y = 8))
print(add.__name__, '|||', add.__doc__)
function add took 3.00s. It run too slow.
13
add ||| None

标签:__,.__,Python,wrapper,datetime,器及,随性,add,fn
来源: https://blog.csdn.net/weixin_44983653/article/details/113789789