python装饰器
本质上是一个python函数,它可以让其它函数在不改动任何代码的前提下增加额外的功能,其返回值也是一个函数对象(函数的指针)- 只要明白一点:在不更改功能代码的前提下,对已经存在的完整功能增加额外的功能
- 实用场景:某个功能需要登录、UV埋点、日志记录等,具体还是看业务需求
示例代码
# -*- coding: utf-8 -*-
from functools import wraps
"""
以下这段代码是装饰器
"""
def decorator(fn):
# fn参数:是你要装饰的函数名(并非函数调用)
print('start use decorator') # 在你开始调用此装饰方法的时候,下面这个输入语句就已经运行了
@wraps
def new_wrapper(*args, **kwargs):
print("Hi, this is wrapper !!")
rv = fn(*args, **kwargs)
return rv
# 返回这个函数
return new_wrapper
# 没有用装饰器
def hello():
print('Hi, this is hello1 func')
# 直接输出'Hi, this is hello1 func'
hello()
# 使用了装饰器
# **这里其实已经会运行装饰器方法里的代码**
@decorator
def hello2():
print('Hi, this is hello2 func')
# 调用 **被装饰后的hello2 方法**,输出内容:
# 'start use decorator' 这个会优先输出
# 'Hi, this is wrapper !!'
# 'Hi, this is hello2 func'
hello2()
那么装饰器使用方法有什么区别那?
# 使用装饰器
@decorator
def hello3():
print('Hi, this is hello3 func')
# 相当于写了以下代码
def hello3():
print('Hi, this is hello3 func')
# 思考:这里会输出什么?,rv的值是什么?
# 控制台会输出:'start use decorator'
# 打印rv的值输出: <function hello3 at 0x1092c5840>
rv = decorator(hello3)
# **而不是**
def hello3():
print('Hi, this is hello3 func')
# 思考:这里没有任何赋值,会输出什么?什么情景适用?
"""
控制台会输出以下内容:
use decorator
<function hello3 at 0x1092c5840>
"""
decorator(hello3)
看到这里你是不是觉得这两种写法输出的都一样啊
且仔细看下面的图
可以看到两者实际上是不一样的对象