How to apply a python decorator to a function?

Possible Duplicate:
Understanding Python decorators

Could you please give a short code example that explains decorators?


def spam(func):
    def wrapped(*args, **kwargs):
        print "SPAM"
        return func(*args, **kwargs)
    return wrapped

@spam #this is the same as doing eggs = spam(eggs)
def eggs():
    print "Eggs?"

注意你也可以使用类来编写装饰器

class Spam(object):
    def __init__(self, func):
        self.func = func

    def __repr__(self):
        return repr(self.func)

    def __call__(self, *args, **kwargs):
        print "SPAM"
        return self.func(*args, **kwargs)

@Spam
def something():
    pass

A decorator takes the function definition and creates a new function that executes this function and transforms the result.

@deco
def do():
    ...

is equivalent to:

do = deco(do)

Example:

def deco(func):
    def inner(letter):
        return func(letter).upper()  #upper
    return inner  # return a function object

#This
@deco
def do(number):
    return chr(number)  # number to letter
#end

# is equivalent to this
def do2(number):
    return chr(number)

do2 = deco(do2)
#end


# 65 <=> 'a'
print(do(65))
print(do2(65))
>>> B
>>> B

To understand the decorator, it is important to notice, that decorator created a new function do which is inner that executes func and transforms the result.

链接地址: http://www.djcxy.com/p/23812.html

上一篇: Python中的@withparser方法意味着什么?

下一篇: 如何将一个Python装饰器应用于一个函数?