8.python-装饰器

# 装饰器
# 主要用于在不改变函数代码的前提下,改变函数的行为,最常见的情况,项目代码日志模块编写

# ===================================================
# 纯手工打造装饰器
def log(func):
    def wrapper(*args, **kwargs):
        print(func.__name__, 'is calling:')
        return func(*args, **kwargs)

    return wrapper


def func():
    print('I am func!')


func_ref = log(func)  # 调用返回wrapper函数
func_ref()  # 执行wrapper函数


# output:
# func is calling:
# I am func!

# ===================================================
# 语法糖打造新式装饰器,大街小巷的相亲们都爱这口

@log
def syntax_sugar_func(name, age, **other):
    print('name:', name, ',age:', age, ',other:', other)


other = {'city': 'wuhan', 'province': 'hubei'}
syntax_sugar_func('Yue', 18, **other)
# output:
# syntax_sugar_func is calling:
# name: Yue ,age: 18 ,other: {'city': 'wuhan', 'province': 'hubei'}
原文地址:https://www.cnblogs.com/wjc920/p/9256156.html