Source From Here
Question
Can one write sth like:
This fails: self in
@self is unknown.
How-To
What you're wanting to do isn't possible. Take, for instance, whether or not the code below looks valid:
It, of course, isn't valid since
self isn't defined at that point. The same goes for Test as it won't be defined until the class itself is defined (which its in the process of). I'm showing you this code snippet because this is what your decorator snippet transforms into. So, as you can see, accessing the instance in a decorator like that isn't really possible since decorators are applied during the definition of whatever function/method they are attached to and not during instantiation.
If you need class-level access, try this:
Execution output:
Question
Can one write sth like:
- class Test(object):
- def _decorator(self, foo):
- foo()
- @self._decorator
- def bar(self):
- pass
How-To
What you're wanting to do isn't possible. Take, for instance, whether or not the code below looks valid:
- class Test(object):
- def _decorator(self, foo):
- foo()
- def bar(self):
- pass
- bar = self._decorator(bar)
If you need class-level access, try this:
- class Test:
- def __init__(self):
- pass
- @classmethod
- def _decorator(clz, foo):
- def dec_method(clz):
- print('Inside clzi({}) decorator'.format(clz))
- foo()
- return dec_method
- @classmethod
- def bar(self):
- print('Invoking bar()')
- Test.bar = Test._decorator(Test.bar)
- to = Test()
- to.bar()
沒有留言:
張貼留言