Yes. In fact, in the sense that you seem to mean, there really is no way to write a decorator that does not have access to self . A decorated function wraps the original function, so it must accept at least the arguments that this function takes (or some arguments from which they can be obtained), otherwise it will not be able to pass the correct arguments to the base function.
You donβt need to do anything special for this, just write a regular decorator:
def deco(func): def wrapper(self, *args, **kwargs): print "I am the decorator, I know that self is", self, "and I can do whatever I want with it!" print "I also got other args:", args, kwargs func(self) return wrapper class Foo(object): @deco def meth(self): print "I am the method, my self is", self
Then you can just use it:
>>> f = Foo() >>> f.meth() I am the decorator, I know that self is <__main__.Foo object at 0x0000000002BCBE80> and I can do whatever I want with it! I also got other args: () {} I am the method, my self is <__main__.Foo object at 0x0000000002BCBE80> >>> f.meth('blah', stuff='crud') I am the decorator, I know that self is <__main__.Foo object at 0x0000000002BCBE80> and I can do whatever I want with it! I also got other args: (u'blah',) {'stuff': u'crud'} I am the method, my self is <__main__.Foo object at 0x0000000002BCBE80>
source share