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

可能重复:
了解Python装饰器

您能否给出一个解释装饰器的简短代码示例?


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

装饰器接受函数定义并创建一个执行此函数并转换结果的新函数。

@deco
def do():
    ...

相当于:

do = deco(do)

例:

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

为了理解装饰器,重要的是要注意,装饰器创建了一个新的函数do,它是执行func并转换结果的内部函数。

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

上一篇: How to apply a python decorator to a function?

下一篇: What is a decorator used for?