Python Study (05)装饰器

来源:互联网 发布:北京网络地板生产厂家 编辑:程序博客网 时间:2024/05/17 18:00

装饰器(decorator)是一种高级Python语法。装饰器可以对一个函数、方法或者类进行加工。在Python中,我们有多种方法对函数和类进行加工,比如在Python闭包中,我们见到函数对象作为某一个函数的返回结果。相对于其它方式,装饰器语法简单,代码可读性高。因此,装饰器在Python项目中有广泛的应用。

装饰器最早在Python 2.5中出现,它最初被用于加工函数和方法这样的可调用对象(callable object,这样的函数对象定义有__call__方法)。在Python 2.6以及之后的Python版本中,装饰器被进一步用于加工类。

装饰函数和方法

先定义两个简单的数学函数,一个用来计算平方和,一个用来计算平方差,在拥有了基本的数学功能之后,我们可能想为函数增加其它的功能,比如打印输入。我们可以改写函数来实现这一点:

# get square sumdef square_sum(a, b):    print("intput:", a, b)    return a**2 + b**2# get square diffdef square_diff(a, b):    print("input", a, b)    return a**2 - b**2print(square_sum(3, 4))print(square_diff(3, 4))

现在,我们使用装饰器来实现上述修改:

def decorator(F):#装饰器接收一个可调用对象作为输入参数    def new_F(a, b):        print("input", a, b)#new_F中,我们增加了打印的功能        return F(a, b)#并通过调用F(a, b)来实现原有函数的功能。    return new_F#并返回一个新的可调用对象。装饰器新建了一个可调用对象,也就是new_F。# get square sum@decoratordef square_sum(a, b):    return a**2 + b**2# get square diff@decoratordef square_diff(a, b):    return a**2 - b**2print(square_sum(3, 4))print(square_diff(3, 4))

定义好装饰器后,我们就可以通过@语法使用了。在函数square_sum和square_diff定义之前调用@decorator,我们实际上将square_sum或square_diff传递给decorator,并将decorator返回的新的可调用对象new_F赋给原来的函数名(square_sum或square_diff)这个函数对象
所以,当我们调用square_sum(3, 4)的时候,就相当于:
square_sum = New_F
square_sum(3, 4)

再例:

即@fun_a与声明fun_b = fun_a(fun_b)等价

def fun_a(ob):    print "hello"    print ob.__doc__    return ob@fun_adef fun_b(a,b):    """this is function b"""    print a+b    print "world"fun_b(3,4)----------------------------------def fun_a(ob):    print "hello"    print ob.__doc__    return obdef fun_b(a,b):    """this is function b"""    print a+b    print "world"fun_b = fun_a(fun_b)  #等价@fun_afun_b(3,4)

小结

Python中的变量名和对象是分离的。变量名可以指向任意一个对象。
从本质上,装饰器起到的就是这样一个重新指向变量名的作用(name binding),让同一个变量名指向一个新返回的可调用对象,从而达到修改可调用对象的目的。
如果我们有其他的类似函数,我们可以继续调用decorator来修饰函数,而不用重复修改函数或者增加新的封装。这样,我们就提高了程序的可重复利用性,并增加了程序的可读性。

装饰类

装饰器被拓展到类。一个装饰器可以接收一个类,并返回一个类,从而起到加工类的效果。

def decorator(aClass):    class newClass:        def __init__(self, age):            self.total_display   = 0            self.wrapped         = aClass(age)        def display(self):            self.total_display += 1            print("total display", self.total_display)            self.wrapped.display()    return newClass"""在decorator中,我们返回了一个新类newClass。在新类中,我们记录了原来类生成的对象(self.wrapped),并附加了新的属性total_display,用于记录调用display的次数。我们也同时更改了display方法。"""@decoratorclass Bird:    def __init__(self, age):        self.age = age    def display(self):        print("My age is",self.age)eagleLord = Bird(5)for i in range(3):    eagleLord.display()