在另一个文件中导入和使用装饰器

时间:2017-11-30 04:47:30

标签: python decorator

我有一个像这样的简单装饰器。但是,当我导入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
>>> 

1 个答案:

答案 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!"