Skip to content

Latest commit

 

History

History
851 lines (622 loc) · 28.4 KB

303.md

File metadata and controls

851 lines (622 loc) · 28.4 KB

#怎样在Python中创建函数装饰器链?

原问题地址:http://stackoverflow.com/questions/739654/how-can-i-make-a-chain-of-function-decorators-in-python

##问题:

我怎样在Python中创建能实现以下功能的两个装饰器?

@makebold
@makeitalic
def say():
    return "Hello"

返回的是:

<b><i>Hello</i></b>

我不想在实际的应用程序中以这种方式来创建HTML,只是想了解装饰器和装饰器链是怎么回事。

##答案 1:

查看参考文献来了解装饰器的应用。这是你所要找的内容:

def makebold(fn):
    def wrapped():
        return "<b>" + fn() + "</b>"
    return wrapped

def makeitalic(fn):
    def wrapped():
        return "<i>" + fn() + "</i>"
    return wrapped

@makebold
@makeitalic
def hello():
    return "hello world"

print hello()     ## returns "<b><i>hello world</i></b>"

##答案 2:

###装饰器基础知识

Python中的函数就是对象

要了解装饰器,你首先必须深知Python中的函数就是对象。这是重要的。让我们通过一个简单的例子来看看为什么:

def shout(word="yes"):
    return word.capitalize()+"!"

print shout()
# outputs : 'Yes!'

# 作为对象,你可以把这个函数赋值给一个变量,像任何其他对象一样

scream = shout

#注意:我们不使用圆括号:不调用函数,我们是把函数“shout”赋给变量“scream”。这意味着你可以从“scream”中调用“shout”:

print scream()
# outputs : 'Yes!'

# 不仅如此,这意味着你可以删除旧的名字'shout',并且仍然可以用'scream'调用这个函数。

del shout
try:
    print shout()
except NameError, e:
    print e
    # outputs: "name 'shout' is not defined"
print scream()
# outputs: 'Yes!'

好的,记住上述内容。我们很快就要用到它。

Python函数的另一个有趣的特性是它们可以在另一个函数里被定义!

def talk():

    # 你可以在"talk"中定义一个动态函数…
    def whisper(word="yes"):
        return word.lower()+"..."

    # 然后马上就能使用它!
    print whisper()

# 如果你每次调用"talk"的时候,"talk"都被定义为"whisper",那么"whisper"就在"talk"中被调用。

talk()
# outputs: 
# "yes..."

# 但"whisper"不存在于"talk"之外:

try:
    print whisper()
except NameError, e:
    print e
    # outputs : "name 'whisper' is not defined"*
    # Python的函数是对象

函数引用

好吧,还在这儿?现在有趣的部分是…

你已经看到了函数就是对象。因此,函数:

  • 可以被赋值给一个变量
  • 可以在另一个函数中定义

这意味着一个函数可以返回另一个函数。看一看!☺

def getTalk(kind="shout"):

# 定义动态函数
    def shout(word="yes"):
        return word.capitalize()+"!"

    def whisper(word="yes") :
        return word.lower()+"...";

# 然后我们返回到其中一个
    if kind == "shout":
    # 不使用"()",我们不是在调用函数,
    # 是在返回函数对象
        return shout  
    else:
        return whisper

# 你怎么使用这个奇怪的工具?
# 获取函数并将它赋给变量
talk = getTalk()

# 你可以看到这里的"talk"是一个函数对象:
print talk
# outputs : <function shout at 0xb7ea817c>

# 此函数所返回的就是这个对象:
print talk()
#outputs : Yes!

# 如果你感到亢奋,你甚至可以直接使用它:
print getTalk("whisper")()
#outputs : yes...

但是,等等…还有更多!

如果你可以返回一个函数,你就可以把一个函数当作参数:

def doSomethingBefore(func): 
    print "I do something before then I call the function you gave me"
    print func()

doSomethingBefore(scream)
#outputs: 
#I do something before then I call the function you gave me
#Yes!

好的,你已经看到了理解装饰器所需要的所有知识。你看,装饰器是“包装器”。这意味着装饰器可以使你在它所装饰的函数之前和之后运行代码,而无需修改函数本身。

装饰器的手动操作

这样来进行装饰器的手动操做:

# 装饰器是一个函数,它把另一个函数作为参数

def my_shiny_new_decorator(a_function_to_decorate):

    # 函数里面,装饰器定义了一个动态函数:the wrapper。
    # 这个函数包含原函数,因此它可以在原函数之前和之后运行代码。
    def the_wrapper_around_the_original_function():

        # 把你希望在原函数被调用之前就执行的代码放在这里
        
        print "Before the function runs"

        # 调用函数(使用括号)
        a_function_to_decorate()

        # 把你希望在原函数被调用之后才执行的代码放在这里

        print "After the function runs"

    # 这时候,"a_function_to_decorate"从未被执行。
    # 回到我们刚才创建的包装器函数。
    # 包装器中包含在原函数被执行之前和之后的函数和代码。它是现成的!
    return the_wrapper_around_the_original_function

#现在想象你创建一个你不想再改动的函数。
def a_stand_alone_function():
    print "I am a stand alone function, don't you dare modify me"

a_stand_alone_function() 
#outputs: I am a stand alone function, don't you dare modify me

#你可以装饰它,以便扩展它的功能。
#只需要把它传递给装饰器,装饰器就会把它动态地装进任何你想要的代码中,
#并且为你返回一个新的可用的函数:

a_stand_alone_function_decorated = my_shiny_new_decorator(a_stand_alone_function)
a_stand_alone_function_decorated()
#outputs:
#Before the function runs
#I am a stand alone function, don't you dare modify me
#After the function runs

现在,你可能希望你每次调用a_stand_alone_function的时候,实际上就是在调用a_stand_alone_function_decorated。这很容易,你只需要借助my_shiny_new_decorator返回的函数覆盖a_stand_alone_function

a_stand_alone_function = my_shiny_new_decorator(a_stand_alone_function)
a_stand_alone_function()

#outputs:
#Before the function runs
#I am a stand alone function, don't you dare modify me
#After the function runs

# 你猜会怎么样?这正是装饰器所实现的功能!

装饰器揭秘

前面的例子中使用了装饰器句法:

@my_shiny_new_decorator
def another_stand_alone_function():
    print "Leave me alone"

another_stand_alone_function()  
#outputs:  
#Before the function runs
#Leave me alone
#After the function runs

是的,就这些,就是这么简单。@decorator只是一个捷径:

another_stand_alone_function = my_shiny_new_decorator(another_stand_alone_function)

装饰器是装饰器设计模式decorator design pattern的Python语言的变体。在Python中,有几种经典的嵌套模式来减轻开发的难度(像迭代器那样)。

当然,你可以把装饰器累积起来:

def bread(func):
    def wrapper():
        print "</''''''\>"
        func()
        print "<\______/>"
    return wrapper

def ingredients(func):
    def wrapper():
        print "#tomatoes#"
        func()
        print "~salad~"
    return wrapper

def sandwich(food="--ham--"):
    print food

sandwich()
# outputs: --ham--
sandwich = bread(ingredients(sandwich))
sandwich()
# outputs:
# </''''''\>
# #tomatoes#
# --ham--
# ~salad~
#<\______/>

使用Python的装饰器句法:

@bread
@ingredients
def sandwich(food="--ham--"):
    print food

sandwich()
#outputs:
#</''''''\>
# #tomatoes#
# --ham--
# ~salad~
#<\______/>

装饰器顺序的设置很重要:

@ingredients
@bread
def strange_sandwich(food="--ham--"):
    print food

strange_sandwich()
#outputs:
##tomatoes#
#</''''''\>
# --ham--
#<\______/>
# ~salad~

现在:回答这个问题…

作为结论,你可以很容易地领会到如何回答这个问题:

# 使字体变粗的装饰器
def makebold(fn):
    # 装饰器所返回的新函数
    def wrapper():
        # 在函数之前和之后插入某些代码
        return "<b>" + fn() + "</b>"
    return wrapper

# 斜体字的装饰器
def makeitalic(fn):
    # The new function the decorator returns
    def wrapper():
        # Insertion of some code before and after
        return "<i>" + fn() + "</i>"
    return wrapper

@makebold
@makeitalic
def say():
    return "hello"

print say() 
#outputs: <b><i>hello</i></b>

# This is the exact equivalent to 
def say():
    return "hello"
say = makebold(makeitalic(say))

这和下面的函数是完全等价的

print say() 
#outputs: <b><i>hello</i></b>

你现在可以快乐地离开,或者多花点心思看一看装饰器的高级应用。

###装饰器应用的更高等级

将参数传递给被装饰的函数

# 这不是魔法,你只需要让包装器传递参数:
def a_decorator_passing_arguments(function_to_decorate):
    def a_wrapper_accepting_arguments(arg1, arg2):
        print "I got args! Look:", arg1, arg2
        function_to_decorate(arg1, arg2)
    return a_wrapper_accepting_arguments

# 因为当你调用被装饰器返回的函数时,你就是在调用包装器,把参数传递给包装器会使包装器把函数传递给被装饰的函数
@a_decorator_passing_arguments
def print_full_name(first_name, last_name):
    print "My name is", first_name, last_name

print_full_name("Peter", "Venkman")
# outputs:
#I got args! Look: Peter Venkman
#My name is Peter Venkman

装饰方法

关于Python的一个有趣的方面是,方法和函数实际上是一样的。唯一的区别是,方法的第一个参数用于引用当前对象(self)。

这意味着你可以用同样的方式为方法创建装饰器!只是要记得把self考虑在内:

def method_friendly_decorator(method_to_decorate):
    def wrapper(self, lie):
        lie = lie - 3            # very friendly, decrease age even more :-)
        return method_to_decorate(self, lie)
    return wrapper

class Lucy(object):

    def __init__(self):
        self.age = 32

    @method_friendly_decorator
    def sayYourAge(self, lie):
        print "I am %s, what did you think?" % (self.age + lie)

l = Lucy()
l.sayYourAge(-3)
#outputs: I am 26, what did you think?

如果你在创建通用装饰器 —— 可以适用于任何函数或方法的装饰器,不管它的参数是什么—— 你只需要使用*args,**kwargs:

def a_decorator_passing_arbitrary_arguments(function_to_decorate):
# 包装器接受任何参数
    def a_wrapper_accepting_arbitrary_arguments(*args, **kwargs):
        print "Do I have args?:"
        print args
        print kwargs
        # Then you unpack the arguments, here *args, **kwargs
        # If you are not familiar with unpacking, check:http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/
        function_to_decorate(*args, **kwargs)
    return a_wrapper_accepting_arbitrary_arguments

@a_decorator_passing_arbitrary_arguments
def function_with_no_argument():
    print "Python is cool, no argument here."

function_with_no_argument()
#outputs
#Do I have args?:
#()
#{}
#Python is cool, no argument here.

@a_decorator_passing_arbitrary_arguments
def function_with_arguments(a, b, c):
    print a, b, c

function_with_arguments(1,2,3)
#outputs
#Do I have args?:
#(1, 2, 3)
#{}
#1 2 3 

@a_decorator_passing_arbitrary_arguments
def function_with_named_arguments(a, b, c, platypus="Why not ?"):
    print "Do %s, %s and %s like platypus? %s" %\
    (a, b, c, platypus)

function_with_named_arguments("Bill", "Linus", "Steve", platypus="Indeed!")
#outputs
#Do I have args ? :
#('Bill', 'Linus', 'Steve')
#{'platypus': 'Indeed!'}
#Do Bill, Linus and Steve like platypus? Indeed!

class Mary(object):

    def __init__(self):
        self.age = 31

    @a_decorator_passing_arbitrary_arguments
    def sayYourAge(self, lie=-3): # You can now add a default value
        print "I am %s, what did you think ?" % (self.age + lie)

m = Mary()
m.sayYourAge()
# outputs
# Do I have args?:
#(<__main__.Mary object at 0xb7d303ac>,)
#{}
#I am 28, what did you think?

把参数传递给装饰器

好,现在你对于把参数传递给装饰器本身有什么看法?

这可能有点怪异,因为装饰器必须接受一个函数作为参数。因此,你不能把被装饰的函数的参数直接传递给装饰器。

在急着去解决问题之前,让我们写一个小小的提示:

# 装饰器是普通函数
def my_decorator(func):
    print "I am an ordinary function"
    def wrapper():
        print "I am function returned by the decorator"
        func()
    return wrapper

# 因此,即使没有任何“@”,你也可以调用它
def lazy_function():
    print "zzzzzzzz"

decorated_function = my_decorator(lazy_function)
#outputs: I am an ordinary function

# It outputs "I am an ordinary function", because that’s just what you do:
# calling a function. Nothing magic.

@my_decorator
def lazy_function():
    print "zzzzzzzz"

#outputs: I am an ordinary function

这是完全一样的。my_decorator被调用。所以当你使用@my_decorator的时候,你就是在告诉Python调用标记为变量my_decorator的函数。

这是很重要的!你所给出的标签可以直接指向装饰器,或者相反。

让我们搞个小把戏。

def decorator_maker():

    print "I make decorators! I am executed only once: " + "when you make me create a decorator."

    def my_decorator(func):

        print "I am a decorator! I am executed only when you decorate a function."

        def wrapped():
            print ("I am the wrapper around the decorated function. "
                  "I am called when you call the decorated function. "
                  "As the wrapper, I return the RESULT of the decorated function.")
            return func()

        print "As the decorator, I return the wrapped function."

        return wrapped

    print "As a decorator maker, I return a decorator"
    return my_decorator

# 让我们创建一个装饰器。它只是一个新函数而已。
new_decorator = decorator_maker()       
#outputs:
#I make decorators! I am executed only once: when you make me create a decorator.
#As a decorator maker, I return a decorator

# 然后我们对这个函数进行装饰
def decorated_function():
    print "I am the decorated function."

decorated_function = new_decorator(decorated_function)
#outputs:
#I am a decorator! I am executed only when you decorate a function.
#As the decorator, I return the wrapped function

# 我们来调用这个函数:
decorated_function()
#outputs:
#I am the wrapper around the decorated function. I am called when you call the decorated function.
#As the wrapper, I return the RESULT of the decorated function.
#I am the decorated function.

这里没有惊喜。

让我们做完全相同的事情,但跳过所有讨厌的中间变量:

def decorated_function():
    print "I am the decorated function."
decorated_function = decorator_maker()(decorated_function)
#outputs:
#I make decorators! I am executed only once: when you make me create a decorator.
#As a decorator maker, I return a decorator
#I am a decorator! I am executed only when you decorate a function.
#As the decorator, I return the wrapped function.

# Finally:
decorated_function()    
#outputs:
#I am the wrapper around the decorated function. I am called when you call the decorated function.
#As the wrapper, I return the RESULT of the decorated function.
#I am the decorated function.

让我们把它缩短:

@decorator_maker()
def decorated_function():
    print "I am the decorated function."
#outputs:
#I make decorators! I am executed only once: when you make me create a decorator.
#As a decorator maker, I return a decorator
#I am a decorator! I am executed only when you decorate a function.
#As the decorator, I return the wrapped function.

#最后: 
decorated_function()    
#outputs:
#I am the wrapper around the decorated function. I am called when you call the decorated function.
#As the wrapper, I return the RESULT of the decorated function.
#I am the decorated function.
decorated_function()    

嘿,你看到了吗?我们在调用函数时使用了 @语句。

所以,返回到带有函数的装饰器。如果我们可以使用函数来生成动态的装饰器,我们就可以将参数传递给函数,对吗?

def decorator_maker_with_arguments(decorator_arg1, decorator_arg2):

    print "I make decorators! And I accept arguments:", decorator_arg1, decorator_arg2

    def my_decorator(func):
        # 这里的传递参数的功能是得益于闭包。 
        # 如果你不喜欢使用闭包,你可以假定它是ok或read:http://stackoverflow.com/questions/13857/can-you-explain-closures-as-they-relate-to-python
        print "I am the decorator. Somehow you passed me arguments:", decorator_arg1, decorator_arg2

        # 不要混淆装饰器参数和函数参数!
        def wrapped(function_arg1, function_arg2) :
            print ("I am the wrapper around the decorated function.\n"
                  "I can access all the variables\n"
                  "\t- from the decorator: {0} {1}\n"
                  "\t- from the function call: {2} {3}\n"
                  "Then I can pass them to the decorated function"
              .format(decorator_arg1, decorator_arg2,
                      function_arg1, function_arg2))
            return func(function_arg1, function_arg2)

        return wrapped

    return my_decorator

@decorator_maker_with_arguments("Leonard", "Sheldon")
def decorated_function_with_arguments(function_arg1, function_arg2):
    print ("I am the decorated function and only knows about my arguments: {0}"
           " {1}".format(function_arg1, function_arg2))

decorated_function_with_arguments("Rajesh", "Howard")
#outputs:
#I make decorators! And I accept arguments: Leonard Sheldon
#I am the decorator. Somehow you passed me arguments: Leonard Sheldon
#I am the wrapper around the decorated function. 
#I can access all the variables 
#   - from the decorator: Leonard Sheldon 
#   - from the function call: Rajesh Howard 
#Then I can pass them to the decorated function
#I am the decorated function and only knows about my arguments: Rajesh Howard

这就是带有参数的装饰器。参数可以被设置为变量:

c1 = "Penny"
c2 = "Leslie"

@decorator_maker_with_arguments("Leonard", c1)
def decorated_function_with_arguments(function_arg1, function_arg2):
    print ("I am the decorated function and only knows about my arguments:"
           " {0} {1}".format(function_arg1, function_arg2))

decorated_function_with_arguments(c2, "Howard")
#outputs:
#I make decorators! And I accept arguments: Leonard Penny
#I am the decorator. Somehow you passed me arguments: Leonard Penny
#I am the wrapper around the decorated function. 
#I can access all the variables 
#   - from the decorator: Leonard Penny 
#   - from the function call: Leslie Howard 
#Then I can pass them to the decorated function
#I am the decorated function and only knows about my arguments: Leslie Howard

正如你可以看到的那样,你可以通过这个小把戏,把参数传递给和任何函数一样的装饰器。如果你愿意,你甚至可以使用*args 和**kwargs。但是记住,装饰器只能被调用一次,也就是当Python导入脚本的时候。在这之后,你就不能动态地设置参数。当你使用“import x”的时候,参数已经被装饰,所以你无法改变什么。

让我们实践一下:修饰装饰器

好吧,作为奖励,我会给你提供一段练习,使得任何一个装饰器接受通用的任何参数。毕竟,为了接受参数,我们用另一个函数创建了我们的装饰器。

我们包装了装饰器。

我们最近有没有看到任何其它的被包装函数?

哦,是的,装饰器!

让我们找一些乐趣,包装一下装饰器:

def decorator_with_args(decorator_to_enhance):
    """ 
    这个函数应该被用作装饰器。
    它必须装饰另一个被确定用作装饰器的函数。
    喝一杯咖啡。
    这将允许任何装饰器接受任意数量的参数,
    这样你就不必每一次都要记着如何去做。
    """

    #我们用相同的把戏来传递参数
    def decorator_maker(*args, **kwargs):

        # 我们动态地创建只接受一个函数的装饰器,但对外隐藏所传递的参数。
        def decorator_wrapper(func):

            # 我们返回到原始装饰器的结果,它毕竟只是一个普通的函数(返回到一个函数)。
            # 唯一的陷阱:装饰器必须有这个独特的签名,否则就无法运行:
            return decorator_to_enhance(func, *args, **kwargs)

        return decorator_wrapper

    return decorator_maker

它的使用方法如下:

# 创建被用作装饰器的函数,并在上面贴上装饰器的标签:-)
# 不要忘记“decorator(func, *args, **kwargs)”
@decorator_with_args 
def decorated_decorator(func, *args, **kwargs): 
    def wrapper(function_arg1, function_arg2):
        print "Decorated with", args, kwargs
        return func(function_arg1, function_arg2)
    return wrapper

# 然后你可以根据自己的意愿,用全新的装饰器来装饰函数。

@decorated_decorator(42, 404, 1024)
def decorated_function(function_arg1, function_arg2):
    print "Hello", function_arg1, function_arg2

decorated_function("Universe and", "everything")
#outputs:
#Decorated with (42, 404, 1024) {}
#Hello Universe and everything

# Whoooot!

如果你不喜欢过长的解释,参见Paolo Bergantino’s的回答(即答案1)。

我知道,你最后一次有这种感觉是在听一个人说“在理解递归之前,你必须先认识递归”的时候。但现在你掌握了装饰器,是不是感觉良好呢?

最佳实践:装饰器

Python 2.4增加了装饰器,所以要确保你的代码在大于或等于 2.4的Python版本上运行。

装饰器会减缓对函数的调用。记住这一点。

你无法撤销对函数的装饰。(有些技巧能用于创建可以撤销的装饰器,但是无人采用。)所以一旦函数被装饰,它所有的代码就都被装饰。

装饰器对函数进行包装,这使函数很难调试。(在大于或等于2.5的Python版本中有所改进;见下文。)

Python 2.5开始有了functools模块。它包括函数functools.wraps()。这个函数把名称、模块和被装饰函数的函数文档字符串拷贝到包装器中。 (有趣的事实:functools.wraps()是装饰器!☺)

# 为了便于调试,堆栈轨迹为你打印出函数`__name__`
def foo():
    print "foo"

print foo.__name__
#outputs: foo

# 有了装饰器的它变得有些凌乱
def bar(func):
    def wrapper():
        print "bar"
        return func()
    return wrapper

@bar
def foo():
    print "foo"

print foo.__name__
#outputs: wrapper

#"functools"对此有所帮助,

import functools

def bar(func):

#我们所说的"wrapper"正在包装"func",魔力开始出现了。

    @functools.wraps(func)
    def wrapper():
        print "bar"
        return func()
    return wrapper

@bar
def foo():
    print "foo"

print foo.__name__
#outputs: foo

如何让装饰器派上用场?

现在的大问题是:我可以用装饰器做什么呢?

装饰器似乎很酷很强大,但有一个实际的例子还是好的。装饰器的使用可以有1000种可能性。经典的用途是从外部静态数据连接库对函数的功能进行扩展(你不能修改它),或者用于调试(你无需修改它,因为它是暂时的)。

你可以遵循DRY (Don't Repeat Yourself)原则用装饰器来扩展几个函数,比如:

def benchmark(func):
    """
    一个记录函数执行时间的装饰器。
    """
import time

    def wrapper(*args, **kwargs):
        t = time.clock()
        res = func(*args, **kwargs)
        print func.__name__, time.clock()-t
        return res
    return wrapper

def logging(func):
    """
    一个记录脚本活动的装饰器。(它实际上只是打印它,但它可以记录!)
    """
    def wrapper(*args, **kwargs):
        res = func(*args, **kwargs)
        print func.__name__, args, kwargs
        return res
    return wrapper


def counter(func):
    """
    一个统计和打印函数运行次数的装饰器
    """
    def wrapper(*args, **kwargs):
        wrapper.count = wrapper.count + 1
        res = func(*args, **kwargs)
        print "{0} has been used: {1}x".format(func.__name__, wrapper.count)
        return res
    wrapper.count = 0
    return wrapper

@counter
@benchmark
@logging
def reverse_string(string):
    return str(reversed(string))

print reverse_string("Able was I ere I saw Elba")
print reverse_string("A man, a plan, a canoe, pasta, heros, rajahs, a coloratura, maps, snipe, percale, macaroni, a gag, a banana bag, a tan, a tag, a banana bag again (or a camel), a crepe, pins, Spam, a rut, a Rolo, cash, a jar, sore hats, a peon, a canal: Panama!")

#outputs:
#reverse_string ('Able was I ere I saw Elba',) {}
#wrapper 0.0
#wrapper has been used: 1x 
#ablE was I ere I saw elbA
#reverse_string ('A man, a plan, a canoe, pasta, heros, rajahs, a coloratura, maps, snipe, percale, macaroni, a gag, a banana bag, a tan, a tag, a banana bag again (or a camel), a crepe, pins, Spam, a rut, a Rolo, cash, a jar, sore hats, a peon, a canal: Panama!',) {}
#wrapper 0.0
#wrapper has been used: 2x
#!amanaP :lanac a ,noep a ,stah eros ,raj a ,hsac ,oloR a ,tur a ,mapS ,snip ,eperc a ,)lemac a ro( niaga gab ananab a ,gat a ,nat a ,gab ananab a ,gag a ,inoracam ,elacrep ,epins ,spam ,arutaroloc a ,shajar ,soreh ,atsap ,eonac a ,nalp a ,nam A

当然,装修器的好处是,你几乎可以在任何内容上立即使用它们,而无需重写。我说过DRY(Don't Repeat Yourself原则,写代码的时候尽量避免重复的实现)。

@counter
@benchmark
@logging
def get_random_futurama_quote():
    from urllib import urlopen
    result = urlopen("http://subfusion.net/cgi-bin/quote.pl?quote=futurama").read()
    try:
        value = result.split("<br><b><hr><br>")[1].split("<br><br><hr>")[0]
        return value.strip()
    except:
        return "No, I'm ... doesn't!"

print get_random_futurama_quote()
print get_random_futurama_quote()

#outputs:
#get_random_futurama_quote () {}
#wrapper 0.02
#wrapper has been used: 1x
#The laws of science be a harsh mistress.
#get_random_futurama_quote () {}
#wrapper 0.01
#wrapper has been used: 2x
#Curse you, merciful Poseidon!

Python本身提供了好几种装饰器:property、staticmethod等。

  • Django使用装饰器来管理高速缓存和视图的权限。
  • Twisted来假冒内联异步函数的调用。

这真是一个大型游乐场。