python装饰器

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

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

1.基本语法

有一个很简单的函数:

1
2
def square(x):
    return x*x

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

1
2
3
4
5
def square(x):
    debug_log = open('debug_log.txt', 'w')
    debug_log.write('Calling %s\n'%square.__name__)
    debug_log.close()
    return x*x

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

1
2
3
4
5
6
7
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)的功能

1
2
3
4
5
6
7
8
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

这样,可以写成:

1
2
square = trace(square) 
square()

或者

1
2
3
4
5
6
7
8
9
10
11
12
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
@trace
def square(x):
    return x*x

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
enable_trace = False
def 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
@trace
def square(x):
    return x*x

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

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

1
2
3
4
5
@foo
@bar
@spam
def func():
    pass

等同于

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

2.接收参数的装饰器

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

1
2
3
4
5
6
7
8
9
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

相当于

1
2
temp = event_handler('BUTTON')
func = temp(func)

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

3.类装饰器

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

1
2
3
4
5
6
7
8
9
registry = {}
def register(cls):
    registry[cls.__clsid__] = cls
    return cls
@register
class Foo(object):
    __clsid__='1'
    def bar(self):
        pass

4.python中一些应用

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

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

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

1
2
3
4
5
6
>>> packitem(1)
[1]
>>> packitem(2)
[1, 2]
>>> packitem(3)
[1, 2, 3]

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

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

1
2
3
4
5
def packitem(x, y=None):
    if y is None:
        y=[]
    y.append(x)
    print y

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

1
2
3
4
5
6
7
8
9
10
def fresh(f):
    d = f.func_defaults
    def refresh(*args, **kwargs):
        f.func_defaults = copy.deepcopy(d)
        return f(*args, **kwargs)
    return refresh
@fresh
def packitem(x, y=[]):
    y.append(x)
    print y

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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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的子类:

1
2
class EuroDate(Date):
    pass

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

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

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

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

1
2
3
4
5
6
7
8
9
10
class Rectangular(object):
    def __init__(self, width, height):
        self.width = width
        self.height = height
    @property
    def area(self):
        return self.width*self.height
 
r = Rectangular(2,3)
print r.area

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

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

1
2
3
4
5
6
7
8
9
10
def wrap(func):
    def call(*args, **kwargs):
        return func(*args, **kwargs)
    return call
@wrap
def foo():
    '''this is a func'''
    pass
print foo.__doc__
print foo.__name__

结果是

1
2
None
call

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

1
2
3
4
5
6
7
8
9
10
11
12
def wrap(func):
    def call(*args, **kwargs):
        return func(*args, **kwargs)
    call.__doc__ = func.__doc__
    call.__name__ = func.__name__
    return call
@wrap
def foo():
    '''this is a func'''
    pass
print foo.__doc__
print foo.__name__

结果正常:

1
2
this is a func
foo

functools的wraps就提供这个功能:

1
2
3
4
5
6
7
8
9
10
11
12
from functools import wraps
def wrap(func):
    @wraps(func)
    def call(*args,**kwargs):
        return func(*args,**kwargs)
    return call
@wrap
def foo():
    '''this is a func'''
    pass
print foo.__doc__
print foo.__name__ 

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

1
2
3
4
5
6
7
8
9
10
11
from contextlib import contextmanager
@contextmanager
def listchange(alist):
    listcopy = list(alist)
    yield listcopy
    alist[:] = listcopy
alist = [1,2,3]
with listchange(alist) as listcopy:
    listcopy.append(5)
    listcopy.append(4)
print alist

  

posted @   再见紫罗兰  阅读(707)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
· Manus的开源复刻OpenManus初探
点击右上角即可分享
微信分享提示