简体   繁体   中英

What is the best way to decorate methods of a Python class?

I am following below conventions to decorate certain methods in a Python class. I am wondering if there are some better ways to do the same. My approach certainly doesn't look good; the call to original member function doesn't look intuitive at all.

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)

If your decorator can only work on methods (because you need access to the instance-specific lock) then just include self in the wrapper signature:

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

I included the @functools.wraps() utility decorator ; it'll copy across various pieces of metadata from the original wrapped function to the wrapper. This is invariably a good idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM