Python3之装饰器原理【和JavaScript的函数作为参数和返回值是一回事,但是有一个坑要注意】

可以参考这篇文章:https://www.cnblogs.com/zhangxinqi/p/8000205.html

错误案例:

def func(c):
    print("func")
    # 特别注意这个地方【错误的原因】
    return c()

@func
def test():
    print("test")


test()


// 输出结果【错误类型】TypeError: 'NoneType' object is not callable
func
Traceback (most recent call last):
test
  File "D:/www/KirinProject/Business/UniappMakeMoneyFirstApp0512/uniapp-Flask/test.py", line 11, in <module>
    test()
TypeError: 'NoneType' object is not callable

正确案例

def func(c):
    print("func")
    # 特别注意这个地方【正确的原因】
    return c

@func
def test():
    print("test")
    return [1,2,3]


test()

// 输出结果:
func
test

进程已结束,退出代码 0

 

错误原因分析:

def func(cFunc):
    print("func")
    这里的c如何是c(),那么外部就不能再执行f()就会报异常
    return cFunc

@func
def test():
    print("test")

def test1():
    print("test")

装饰器调用
f = test  先把test的函数传入func,返回来的f依然是一个函数【必须是上面的cFunc没有执行】
f() 如果上面的cFunc是cFunc(),那么这里的f()就是一个NoneType()类型肯定报错,NoneType不是一个可调用的函数

传统的调用【运行test()方法和运行func(test1)()是一回事】
f1 = func(test1)()

猜你喜欢

转载自blog.csdn.net/weixin_43343144/article/details/91039970
今日推荐