python:为什么在decorator中使用包装?

2024-05-12 19:27:31 发布

您现在位置:Python中文网/ 问答频道 /正文

def synchronized(func):
    """Decorator for storage-access methods, which synchronizes on a threading
    lock. The parent object must have 'is_closed' and '_sync_lock' attributes.
    """

    @wraps(func)
    def synchronized_wrapper(self, *args, **kwargs):
        with self._sync_lock:
           return func(self, *args, **kwargs)

    return synchronized_wrapper

代码在whoosh/src中/实用程序.py,我无法理解synchronized_wrapper的效果以及synchronized_wrapper(self,*args,**kwargs)中的参数从何而来。谁能给我点建议吗?在


Tags: selflockforreturnaccessdefargsdecorator
2条回答

@wraps修饰符只是函数闭包(带参数转发)的语法糖。*args表示位置参数的元组,**kwargs表示传递给func的所有关键字参数的dict。在

因此,如果你有:

def f(foo, bar=None):
    ...

并且做到了:

^{pr2}$

基本上就像打电话:

f(a, bar=z)

但是在“with self._sync_lock:”上下文管理器中

对函数进行装饰会导致基于反射的操作出现问题,@wraps的设计目的是使封装的函数真正模拟原始函数。The link提供的luciam具有适用信息。在

相关问题 更多 >