为什么装饰器必须在调用之前声明,而函数却不需要?

Why do decorators have to be declared before they're called, but functions don't?

我在 Python 2.7 中有以下示例:

import time
@timing
def my_test_function():
    return 5+5
def timing(f):
    def wrap(*args):
        time1 = time.time()
        ret = f(*args)
        time2 = time.time()
        print '%s function took %0.3f ms' % (f.func_name, (time2-time1)*1000.0)
        return ret
    return wrap

这失败了。 NameError: name 'timing' is not defined

然而,这并没有失败,显然:

def a():
    result = b()
    return result
def b():
    return 'foo'

如果装饰器是函数,这里有什么区别?

函数do必须在调用前声明。唯一的区别是装饰器通常比其他函数更早被调用。

在您的示例中,装饰器在创建 my_test_function 时调用(可能是导入时间),而 b 在调用 a 之前不会被调用。

如果您执行以下操作,您会看到 NameError 就像装饰器案例一样:

def a():
    result = b()
    return result

a()  # Call `a` before `b` has been defined.

def b():
    return 'foo'