我有一个像这样的简单装饰器。但是,当我导入python文件时,它会立即运行,我无法再次调用该函数。如何使用装饰器?
def plain_decorator(func):
def decorated_func():
print "Decorating"
func()
print "Decorated"
return decorated_func()
@plain_decorator
def hw():
print "Hello Decorators!"
>>> import decorator_ex2 as d
Decorating
Hello Decorators!
Decorated
>>> d.hw()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable
>>>
答案 0 :(得分:2)
尝试使用它,因为你从外部(plain_decorator)函数返回时调用你的内部(decorated_func)函数
def plain_decorator(func):
def decorated_func():
print "Decorating"
func()
print "Decorated"
return decorated_func
@plain_decorator
def hw():
print "Hello Decorators!"