Python装饰器本质250220

  • 定义一个函数,在不修改这个函数的代码的情况下,让函数执行前后会有新的内容加入
python 复制代码
def func():
    print("func")
    return
def outer():
    def inner():
        print("new code before")
        func()
        print("new code after")
        return
    return inner
func = outer()# 执行到这一步,func指向变为inner
func()# 相当于执行inner(),而调用inner()时,打印before后,再调用第7行func(),就是又调用了inner(),如此反复,耗尽函数栈
  • 上述的写法会变成死循环,在第11行相当于修改了func函数的指向,导致反复调用outer函数
  • 上述写法要改写
python 复制代码
def func():
    print("func")
    return [1, 2, 3]
def outer(arg):
    def inner():
        print("before")
        res = arg()
        print("after")
        return res
    return inner
func = outer(func)# 经过outer包装为闭包,括号内的func还是指向原定义的函数,等号左边func是指向了inner,左右两个func是不同的
func()# 
  • 还是不能理解闭包的形式
  • 上述写法的逻辑是之前定义了一个函数,将这个函数包装一下,从而在不改变其最一开始定义的内容的情况下,再次调用这个函数(函数名相同),会在前和后添加其它逻辑与代码
相关推荐
databook30 分钟前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室1 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三2 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户2519162427116 小时前
Python之语言特点
python
刘立军6 小时前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机10 小时前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机11 小时前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i12 小时前
django中的FBV 和 CBV
python·django
c8i12 小时前
python中的闭包和装饰器
python
这里有鱼汤15 小时前
小白必看:QMT里的miniQMT入门教程
后端·python