Python 示例装饰程序错误
我试图理解Python装饰器,并编写了以下代码:Python 示例装饰程序错误,python,python-decorators,Python,Python Decorators,我试图理解Python装饰器,并编写了以下代码: def hello_world(fn): print('hello world') fn() pass @hello_world def decorate(): print('hello decoatrion') return decorate() 我的目标是在“hello装饰”之前打印“hello world”,但输出如下: 你好,世界 你好,decoatrion 回溯最近一次呼叫上次: 文件tes
def hello_world(fn):
print('hello world')
fn()
pass
@hello_world
def decorate():
print('hello decoatrion')
return
decorate()
我的目标是在“hello装饰”之前打印“hello world”,但输出如下:
你好,世界
你好,decoatrion
回溯最近一次呼叫上次:
文件test_decortor.py,第11行,in
装饰
TypeError:“非类型”对象不可调用
装饰器必须返回装饰过的函数。你可能想要这样的东西:
def hello_world(fn):
def inner():
print('hello world')
fn()
return inner
@hello_world
def decorate():
print('hello decoatrion')
return
decorate()
#output: hello world
# hello decoatrion
Decorator语法是
decorated = decorate(decorated)
因此,如果你有:
def hello_world(fn):
print('hello world')
fn()
pass
def decorate():
print('hello decoatrion')
return
decorate = hello_world(decorate)
您应该看到问题所在,还请注意,pass在这里什么都不做
def hello_world(fn):
def says_hello():
print('hello world')
return fn()
return says_hello
def decorate():
print('hello decoration')
decorate = hello_world(decorate)
我会做你想做的。或者你可以写:
@hello_world
def decorate():
print('hello decoration')
好的,那么你的问题是什么呢?装饰器的可能副本返回的是无,而不是装饰函数。签出,以及它本身。文档参考: