python装饰器,,myfunc=wra


myfunc=wrapper(myfunc)是一种很常见的修改其它函数的方法。从python2.4开始,可以在定义myfunc的def语句之前写@wrapper。

这些封装函数就被称为装饰器Decorator,其主要用途是包装另一个函数或类。这种包装的首要目的是透明的修改或增强被包装对象的行为。

1.基本语法

有一个很简单的函数:

def square(x):    return x*x

如果想追踪函数的执行情况:

def square(x):    debug_log=open(‘debug_log.txt‘,‘w‘)    debug_log.write(‘Calling %s\n‘%square.__name__)    debug_log.close()    return x*x

功能上实现了追踪,但如果要追踪很多函数的执行情况,显然不可能为每个函数都添加追踪代码,可以将追踪代码提取出来:

def trace(func,*args,**kwargs):    debug_log=open(‘debug_log.txt‘,‘w‘)    debug_log.write(‘Calling %s\n‘%func.__name__)    result=func(*args,**kwargs)    debug_log.write(‘%s returned %s\n‘%(func.__name__,result))    debug_log.close()trace(square,2)

这样调用square()变成了调用trace(square),如果square()在N处被调用了,你要修改N次,显然不够简洁,我们可以使用闭包函数使square()发挥trace(square)的功能

def trace(func):    def callfunc(*args,**kwargs):        debug_log=open(‘debug_log.txt‘,‘w‘)        debug_log.write(‘Calling %s: %s ,%s\n‘%(func.__name__,args,kwargs))        result=func(*args,**kwargs)        debug_log.write(‘%s returned %s\n‘%(func.__name__,result))        debug_log.close()    return callfunc

这样,可以写成:

square=trace(square)  square()

或者

def trace(func):    def callfunc(*args,**kwargs):        debug_log=open(‘debug_log.txt‘,‘w‘)        debug_log.write(‘Calling %s: %s ,%s\n‘%(func.__name__,args,kwargs))        result=func(*args,**kwargs)        debug_log.write(‘%s returned %s\n‘%(func.__name__,result))        debug_log.close()        return result    return callfunc@tracedef square(x):    return x*x 

还可以根据自己的需求关闭或开启追踪功能:

enable_trace=Falsedef trace(func):    if enable_trace:        def callfunc(*args,**kwargs):            debug_log=open(‘debug_log.txt‘,‘w‘)            debug_log.write(‘Calling %s: %s ,%s\n‘%(func.__name__,args,kwargs))            result=func(*args,**kwargs)            debug_log.write(‘%s returned %s\n‘%(func.__name__,result))            debug_log.close()        return callfunc    else:        return func@tracedef square(x):    return x*x 

这样,利用enable_trace变量禁用追踪时,使用装饰器不会增加性能负担。

使用@时,装饰器必须出现在需要装饰的函数或类定义之前的单独行上。可以同时使用多个装饰器。

@foo@bar@spamdef func():    pass

等同于

func=foo(bar(spam(func)))

2.接收参数的装饰器

装饰器也可以接收参数,比如一个注册函数:

event_handlers={}def event_handler(event):    def register_func(func):        event_handlers[event]=func        return func    return register_func@event_handler(‘BUTTON‘)def func():    pass

相当于

temp=event_handler(‘BUTTON‘)func=temp(func)

这样的装饰器函数接受带有@描述符的参数,调用后返回接受被装饰函数作为参数的函数。

3.类装饰器

类装饰器接受类为参数并返回类作为输出。

registry={}def register(cls):    registry[cls.__clsid__]=cls    return cls@registerclass Foo(object):    __clsid__=‘1‘    def bar(self):        pass

4.python中一些应用

4.1 刷新函数中默认参数值:

def packitem(x,y=[]):        y.append(x)    print y

当用列表作为函数参数的默认值时,会发生难以预料的事情。

>>> packitem(1)[1]>>> packitem(2)[1, 2]>>> packitem(3)[1, 2, 3]

因为python会为函数的可选参数计算默认值,但只做一次,所以每次append元素都是向同一个列表中添加,显然不是我们的本意。

一般情况下,python推荐不使用可变的默认值,惯用解决方法是:

def packitem(x,y=None):    if y is None:        y=[]    y.append(x)    print y

还有一种解决方法,就是使用装饰器了:

def fresh(f):    d=f.func_defaults    def refresh(*args,**kwargs):        f.func_defaults=copy.deepcopy(d)        return f(*args,**kwargs)    return refresh@freshdef packitem(x,y=[]):    y.append(x)    print y

用装饰器函数深拷贝被装饰函数的默认参数。

4.2 python有几个内置装饰器staticmethod,classmethod,property,作用分别是把类中定义的实例方法变成静态方法、类方法和类属性。

静态方法可以用来做为有别于__init__的方法来创建实例。

class Date(object):    def __init__(self,year,month,day):        self.year=year        self.month=month        self.day=day    @staticmethod    def now():        t=time.localtime()        return Date(t.year,t.mon,t.day)    @staticmethod    def tomorrow():        t=time.localtime(time.time()+86400)        return Date(t.year,t.mon,t.day)now=Date.now()tom=Date.tomorrow()

类方法可以把类本身作为对象进行操作:

如果创建一个Date的子类:

class EuroDate(Date):    pass

EuroDate.now()产生是一个Date实例而不是EuroDate实例,为避免这种情况,可以:

class Date(object):    @classmethod    def now(cls):        t=time.localtime()        return cls(t.year,t.mon,t.day)

这样产生的就是子类对象了。

特性可以用函数来模拟属性。

class Rectangular(object):    def __init__(self,width,height):        self.width=width        self.height=height    @property    def area(self):        return self.width*self.heightr=Rectangular(2,3)print r.area

4.3 functools模块中定义的@wraps(func)可以将函数func的名称,文档字符串等属性传递给要定义的包装器函数。

装饰器包装函数可能会破坏与文档字符串相关的帮助功能:

def wrap(func):    def call(*args,**kwargs):        return func(*args,**kwargs)    return call@wrapdef foo():    ‘‘‘this is a func‘‘‘    passprint foo.__doc__print foo.__name__

结果是

Nonecall

 解决办法是编写可以传递函数名称和文档字符串的装饰器函数:

def wrap(func):    def call(*args,**kwargs):        return func(*args,**kwargs)    call.__doc__=func.__doc__    call.__name__=func.__name__    return call@wrapdef foo():    ‘‘‘this is a func‘‘‘    passprint foo.__doc__print foo.__name__

结果正常:

this is a funcfoo

functools的wraps就提供这个功能:

from functools import wrapsdef wrap(func):    @wraps(func)    def call(*args,**kwargs):        return func(*args,**kwargs)    return call@wrapdef foo():    ‘‘‘this is a func‘‘‘    passprint foo.__doc__print foo.__name__ 

4.4 contexlib模块中定义的contextmanager(func)可以根据func创建一个上下文管理器。

from contextlib import contextmanager@contextmanagerdef listchange(alist):    listcopy=list(alist)    yield listcopy    alist[:]=listcopyalist=[1,2,3]with listchange(alist) as listcopy:    listcopy.append(5)    listcopy.append(4)print alist

  

python装饰器,布布扣,bubuko.com

python装饰器

评论关闭