2017年8月20日 星期日

[ Python 常見問題 ] Python decorators in classes

Source From Here 
Question 
Can one write sth like: 
  1. class Test(object):  
  2.     def _decorator(self, foo):  
  3.         foo()  
  4.   
  5.     @self._decorator  
  6.     def bar(self):  
  7.         pass  
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: 
  1. class Test(object):  
  2.   
  3.     def _decorator(self, foo):  
  4.         foo()  
  5.   
  6.     def bar(self):  
  7.         pass  
  8.     bar = self._decorator(bar)  
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: 
  1. class Test:  
  2.     def __init__(self):  
  3.         pass  
  4.   
  5.     @classmethod  
  6.     def _decorator(clz, foo):  
  7.         def dec_method(clz):  
  8.             print('Inside clzi({}) decorator'.format(clz))  
  9.             foo()  
  10.         return dec_method  
  11.   
  12.     @classmethod  
  13.     def bar(self):  
  14.         print('Invoking bar()')  
  15.   
  16. Test.bar = Test._decorator(Test.bar)  
  17.   
  18. to = Test()  
  19. to.bar()  
Execution output: 
Inside clzi(<__main__.Test object at 0x7f43a56d21d0>) decorator 
Invoking bar()


沒有留言:

張貼留言

[ Python 文章收集 ] SQLAlchemy quick start with PostgreSQL

Source From   Here   Preface   This is a quick tutorial for getting started with   SQLAlchemy Core API .   Prerequisites   In this quick st...