Yes. Instead of passing an instance attribute during class definition, check it at runtime:
def check_authorization(f): def wrapper(*args): print args[0].url return f(*args) return wrapper class Client(object): def __init__(self, url): self.url = url @check_authorization def get(self): print 'get' >>> Client('http://www.google.com').get() http://www.google.com get
The decorator intercepts the arguments of the method; the first argument is the instance, so it reads an attribute of this. You can pass the attribute name as a string to the decorator and use getattr if you do not want to hardcode the attribute name:
def check_authorization(attribute): def _check_authorization(f): def wrapper(self, *args): print getattr(self, attribute) return f(self, *args) return wrapper return _check_authorization
li.davidm Jul 30 '12 at 23:38 2012-07-30 23:38
source share