Introduction to the correct implementation of Python AOP

Source: Internet
Author: User

How can we implement Python AOP correctly and efficiently to help our program development? First, we need to use metaclass to implement this technical application. The specific operation steps will be presented here, hoping to help you.

In fact, it is very easy to implement AOP in a very dynamic language such as Python, so we should first define a metaclass

Then we need to dynamically implant the method to the front and back of the method to be called when _ new _) metaclass.

The specific Python AOP implementation code is as follows:

 
 
  1. _ Author __= "alex"
  2. _ Date _ = "$23:54:11 $"
  3. _ Name __= "pyAOP"
  4. '''
  5. This metaclass is the basis for Implementing AOP.
  6. '''
  7. Class pyAOP (type ):
  8. '''
  9. This empty method is used to initialize beforeop and afterop to function reference.
  10. '''
  11. Def nop (self ):
  12. Pass
  13. '''
  14. The following two variables are class variables, that is, the variables that store the addresses of the two functions to be implanted.
  15. '''
  16. Beforeop = nop
  17. Afterop = nop
  18. '''
  19. Set the class functions of the first and second embedded Functions
  20. '''
  21. @ Classmethod
  22. Def setbefore (self, func ):
  23. PyAOP. beforeop = func
  24. @ Classmethod
  25. Def setafter (self, func ):
  26. PyAOP. afterop = func
  27. '''
  28. Initialize the metaclass function, which is the fourth parameter,
    Dict through this parameter we can modify the class attribute method)
  29. '''
  30. Def _ new _ (mcl, name, bases, dict ):
  31. From types import FunctionType # The funpes type of the load type module
  32. Obj = object () # define a variable of an empty object
  33. '''
  34. This is the method to be implanted. the func parameter is the function we want to call.
  35. '''
  36. Def AOP (func ):
  37. '''
  38. We use this function to replace the function to be called.
  39. '''
  40. Def wrapper (* args, ** kwds ):
  41. PyAOP. beforeop (obj) # Call the prefix Function
  42. Value = func (* args, ** kwds) # Call the function to be called
  43. PyAOP. afterop (obj) # Call the post Function
  44. Return value # return
  45. Return wrapper
  46. # Search for the function to be called in the member list of the class
  47. For attr, value in dict. iteritems ():
  48. If isinstance (value, FunctionType ):
  49. Dict [attr] = AOP (value) # Replace it with the function AOP after finding it
  50. Obj = super (pyAOP, mcl). _ new _ (mcl, name, bases, dict)
    # Call _ new _ () of the parent class to create self
  51. Return obj

If we want to intercept A method call for Class A, this is the case:

 
 
  1. class A(object):  
  2. __metaclass__ = pyaop 
  3. def foo(self):  
  4. total = 0 
  5. for i in range(100000):  
  6. totaltotal = total+1  
  7. print total  
  8. def foo2(self):  
  9. from time import sleep  
  10. total = 0 
  11. for i in range(100000):  
  12. totaltotal = total+1  
  13. sleep(0.0001)  
  14. print total 

Finally, we only need:

 
 
  1. def beforep(self):  
  2. print('before')  
  3. def afterp(self):  
  4. print('after')  
  5. if __name__ == "__main__":  
  6. pyAOP.setbefore(beforep)  
  7. pyAOP.setafter(afterp)  
  8. a=A()  
  9. a.foo()  
  10. a.foo2() 

In this way, the following results are obtained during code execution:

 
 
  1. before  
  2. 100000  
  3. after  
  4. before  
  5. 100000  
  6. after 

The above is our introduction to Python AOP.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.