this blog article中,他们使用结构:

  @measured
  def some_func():
    #...
  # Presumably outputs something like "some_func() is finished in 121.333 s" somewhere

这个@measured指令似乎不适用于原始python。这是怎么一回事?
更新:我从triptypch看到@something是有效的,但是我在哪里可以找到@measured,它是在某个库中,还是这个博客的作者使用了他自己的私有代码库中的一些东西?

最佳答案

@measured使用名为measured的函数或类装饰some-func()函数。@是decorator语法,measured是decorator函数名。
decorator可能有点难理解,但它们基本上是用来包装函数的代码,或者将代码注入函数。
例如,测量的函数(用作装饰器)可能是这样实现的。。。

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

decorator语法只是执行以下操作的一种更短、更整洁的方法:
def some_func():
    print "This is my original function!"

some_func = measured(some_func)

Python中包含一些decorator,例如staticmethod-但是measured不是其中之一:
>>> type(measured)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'measured' is not defined

检查projectsimport语句以查看函数或类来自何处。如果它使用from blah import *您将需要检查所有这些文件(这就是为什么不鼓励使用import *的原因),或者您可以执行类似grep -R def measured *的操作

关于python - @measured是标准装饰器吗?它在哪个库中?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/382624/

10-12 23:17