@measured是标准的装饰者吗?它在哪个图书馆?

时间:2008-12-20 00:04:42

标签: python decorator

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

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

这个@measured指令似乎不适用于原始python。它是什么?

更新:我从Triptych看到@something是有效的,但我在哪里可以找到@measured,是在某个地方的某个库中,还是这个博客的作者使用他自己私人的东西代码库?

3 个答案:

答案 0 :(得分:13)

@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 *

之类的操作

答案 1 :(得分:3)

是的,这是真的。这是一个功能装饰者。

Python中的函数修饰器是将函数作为单个参数的函数,并在其中返回一个新函数。

@classmethod@staticmethod是两个内置函数装饰器。

Read more »

答案 2 :(得分:0)

measured是在该代码起作用之前必须定义的函数的名称。

通常,用作装饰器的任何函数都必须接受函数并返回函数。该函数将被替换为将其传递给装饰器的结果 - 在这种情况下为measured()。