Python 装饰器 爆栈

def is_root(root):
    def deco(func):
        def wrapper(*args,**kwargs):
            # if root == 1:
            res = add_student(*args,**kwargs)
            # else:
            #     res = -1
            #     print('未获取root信息,error')
            return res
        return wrapper
    return deco

@is_root(root = 1) #deco
def add_student(x):
    print('添加学生信息',x)
    return 1

print(add_student(1))

要在add的基础上增加判断root的功能

你add_student无限递归调用,又没有设置终止条件自然会爆栈

@is_root(root = 1) #deco
def add_student(x):
    print('添加学生信息',x)
    return 1

实际上,上面程序完全等价于下面的程序:

def add_student(x):
    print('添加学生信息',x)
    return 1
add_student = is_root(root=1)(add_student)

add_student被重新赋值成wrapper函数.
在wrapper函数中调用add_student就等同调用wrapper函数自己,就成了递归调用.
而func传参的是原本的add_student,调用func函数不是递归调用.

如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!

img

解决了
第5行写错了,那个add_student 应该改成func但是还不明白这样做为什么会爆栈,有无大佬解释下

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632