Python装饰器
Posted corecoder
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python装饰器相关的知识,希望对你有一定的参考价值。
原函数
def foo(): print(‘i am foo‘)
增加函数功能
def foo(): print(‘i am foo‘) print(‘i am running‘)
不修改原函数代码的同时增加函数功能
def log(func): func() print(‘i am running‘) def foo(): print(‘i am foo‘) log(foo)
函数名不变
foo = log(foo)
foo()
则需要返回一个函数
def log(func): def inner(): func() print(‘i am running‘) return inner def foo(): print(‘i am foo‘) foo = log(foo) foo()
语法糖
def log(func): def inner(): func() print(‘i am running‘) return inner @log def foo(): print(‘i am foo‘) foo()
原函数有参数
def log(func): def inner(a, b): func(a, b) print(‘i am running‘) return inner @log def foo(a, b): print(a, b) foo(1, 2)
装饰器不用随着原函数的参数修改而修改
def log(func): def inner(*args): func(*args) print(‘i am running‘) return inner @log def foo(a, b): print(a, b) foo(1, 2)
装饰器带参数
def outer(x): def log(func): def inner(*args): print(x) func(*args) print(‘i am running‘) return inner return log @outer(0) def foo(a, b): print(a, b) foo(1, 2)
相当于
foo = outer(0)(foo)
函数名更正
def outer(x): def log(func): def inner(*args): inner.__name__ = func.__name__ print(x) func(*args) print(‘i am running‘) return inner return log @outer(0) def foo(a, b): print(a, b) foo(1, 2)
更好的做法
import functools def outer(x): def log(func): @functools.wraps(func) def inner(*args): print(x) func(*args) print(‘i am running‘) return inner return log @outer(0) def foo(a, b): print(a, b) foo(1, 2)
以上是关于Python装饰器的主要内容,如果未能解决你的问题,请参考以下文章