@measured 使用名为 measured 的函数或类来装饰 some_func() 函数。 @ 是装饰器语法,measured 是装饰器函数名。
装饰器可能有点难以理解,但它们基本上用于将代码包装在函数周围,或者将代码注入其中。
例如测量的函数(用作装饰器)可能是这样实现的......
import time
def measured(orig_function):
# When you decorate a function, the decorator func is called
# with the original function as the first argument.
# You return a new, modified function. This returned function
# is what the to-be-decorated function becomes.
print "INFO: This from the decorator function"
print "INFO: I am about to decorate %s" % (orig_function)
# This is what some_func will become:
def newfunc(*args, **kwargs):
print "INFO: This is the decorated function being called"
start = time.time()
# Execute the old function, passing arguments
orig_func_return = orig_function(*args, **kwargs)
end = time.time()
print "Function took %s seconds to execute" % (end - start)
return orig_func_return # return the output of the original function
# Return the modified function, which..
return newfunc
@measured
def some_func(arg1):
print "This is my original function! Argument was %s" % arg1
# We call the now decorated function..
some_func(123)
#.. and we should get (minus the INFO messages):
This is my original function! Argument was 123
# Function took 7.86781311035e-06 to execute
装饰器语法只是执行以下操作的一种更短更简洁的方式:
def some_func():
print "This is my original function!"
some_func = measured(some_func)
Python 中包含一些装饰器,例如 staticmethod - 但 measured 不是其中之一:
>>> type(measured)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'measured' is not defined
检查项目import 语句以查看函数或类的来源。如果它使用from blah import *,您需要检查所有这些文件(这就是不鼓励使用import * 的原因),或者您可以执行grep -R def measured * 之类的操作