Python Decorator With Arguments And Accessing Class Instance
I have a class defined as follows: class SomeViewController(BaseViewController): @requires('id', 'param1', 'param2') @ajaxGet def create(self): #do something he
Solution 1:
Yes. In fact, in the sense you seem to mean, there isn't really a way to write a decorator that doesn't have access to self
. The decorated function wraps the original function, so it has to accept at least the arguments that that function accepts (or some arguments from which those can be derived), otherwise it couldn't pass the right arguments to the underlying function.
There is nothing special you need to do to do this, just write an ordinary 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>
Post a Comment for "Python Decorator With Arguments And Accessing Class Instance"