<分区>
我刚刚开始使用 Python,并且刚刚接触过装饰器。我编写了以下代码,模仿我所看到的,并且它有效:
def decorator_function(passed_function):
def inner_decorator():
print('this happens before')
passed_function()
print('this happens after')
return inner_decorator
@decorator_function
def what_we_call():
print('The actual function we called.')
what_we_call()
但后来我写了这个,它抛出了错误:
def decorator_function(passed_function):
print('this happens before')
passed_function()
print('this happens after')
@decorator_function
def what_we_call():
print('The actual function we called.')
what_we_call()
那么,为什么我们需要在装饰器函数中包含内部嵌套函数?它有什么作用?只使用第二个语法不是更简单吗?我没有得到什么?
有趣的是两者都有相同的(正确的)输出,但第二个也有错误文本,说“TypeError: 'NoneType' object is not callable”
请使用适合刚开始使用 Python 的人的语言和示例,Python 是他的第一门编程语言,也是 OOP 的新手! :) 谢谢。