Contents

Python中的装饰器

本文采用知识共享署名 4.0 国际许可协议进行许可,转载时请注明原文链接,图片在使用时请保留全部内容,可适当缩放并在引用处附上图片所在的文章链接。

装饰器(Decorators)

装饰器(Decorator)是Python中一个重要部分,它本质上是一个函数,不同于普通函数,装饰器的返回值是一个函数对象。通过利用装饰器,我们可以让其他函数在不做任何代码改动的情况下增加额外的功能,同时也能够让代码更加简洁。

1
2
3
4
5
6
def decorator(func):
   return func

@decorator
def some_func():
    pass

等同于

1
2
3
4
5
6
7
def decorator(func):
    return func

def some_func():
    pass

some_func = decorator(some_func)

举例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Pizza(object):
    def __init__(self): # __init__ : 构造方法,通过类创建对象时,自动触发执行。
        self.toppings = []

    def __call__(self, topping): # __call__ : 对象后面加括号,触发执行。
        # When using '@instance_of_pizza' before a function definition
        # the function gets passed onto 'topping'.
        self.toppings.append(topping())

    def __repr__(self): # __repr__ : 打印,转换
        return str(self.toppings) + " " + str(1)

    def __str__(self): # __str__ : 如果一个类中定义了__str__方法,那么在打印 对象 时,默认输出该方法的返回值。有点像java中的toString方法。
        return str(self.toppings)+ " " + str(2)

pizza = Pizza()

@pizza
def cheese():
    return 'cheese'
@pizza
def sauce():
    return 'sauce'

print (pizza)
# ['cheese', 'sauce'] 2