Can you create a decorator inside a class that will see the classes methods and variables?
The decorator here doesnt see: self.longcondition()
class Foo:
def __init__(self, name):
self.name = name
# decorator that will see the self.longcondition ???
class canRun(object):
def __init__(self, f):
self.f = f
def __call__(self, *args):
if self.longcondition(): # <-------- ???
self.f(*args)
# this is supposed to be a very long condition :)
def longcondition(self):
return isinstance(self.name, str)
@canRun # <------
def run(self, times):
for i in xrange(times):
print "%s. run... %s" % (i, self.name)
You can have it be a class but you need to use the descriptor protocol
You always need to use a descriptor when you want to decorate class methods with a class instance using the
__call__method. The reason for this is that there will only be oneselfpassed in which refers to the instance of the decorating class and not the instance of the decorated method.