gpt4 book ai didi

python - 装饰 Python 类方法的最佳方式是什么?

转载 作者:行者123 更新时间:2023-12-01 04:41:55 29 4
gpt4 key购买 nike

我遵循以下约定来装饰 Python 类中的某些方法。我想知道是否有一些更好的方法可以做到同样的事情。我的方法看起来当然不太好;对原始成员函数的调用看起来一点也不直观。

from threading import Lock

def decobj(fun):
def fun2(*args, **kwards):
with args[0].lock:
print 'Got the lock'
fun(*args, **kwards)
return fun2

class A:
def __init__(self, a):
self.lock = Lock()
self.x = a
pass

@decobj
def fun(self, x, y):
print self.x, x, y


a = A(100)
a.fun(1,2)

最佳答案

如果您的装饰器只能在方法上工作(因为您需要访问特定于实例的锁),那么只需在包装器签名中包含 self 即可:

from functools import wraps

def decobj(func):
@wraps(func)
def wrapper(self, *args, **kwards):
with self.lock:
print 'Got the lock'
func(self, *args, **kwards)
return wrapper

我添加了@functools.wraps() utility decorator ;它将把各种元数据从原始包装函数复制到包装器。这总是一个好主意。

关于python - 装饰 Python 类方法的最佳方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30459605/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com