python 装饰器与AOP

来源:互联网 发布:临汾直销软件 编辑:程序博客网 时间:2024/05/16 10:34
缓存

[python] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. from functools import wraps  
  2.   
  3. lineseq = '==' * 20  
  4.   
  5. def memo( func ):  
  6.       
  7.     cache = {}  
  8.  
  9.     @wraps( func )  
  10.     def wrapper( *args ):  
  11.         result = cache.get( args )  
  12.         if result is None:  
  13.             result = func( *args )  
  14.             cache[args] = result  
  15.         return result  
  16.   
  17.     return wrapper  
  18.  
  19.  
  20. @memo  
  21. def fib( n ):  
  22.     if n < 2:  
  23.         return n  
  24.     return fib( n - 1 ) + fib( n - 2 )  
  25.   
  26. print fib( 10 )  


注册函数信息

[python] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. import time  
  2.   
  3. def logger( func ):  
  4.      
  5.     @wraps( func )  
  6.     def deco( *args, **kwargs ):  
  7.         start_time = time.time()  
  8.         result = func( *args, **kwargs )  
  9.         end_time = time.time()  
  10.         print 'function = {0}'.format( func.__name__ )  
  11.         print 'arguments = {0}{1}'.format( args, kwargs )  
  12.         print 'return = {0}'.format( result )  
  13.         print 'time = %.6f sec'%( start_time - end_time )  
  14.         return result  
  15.     return deco  
  16.  
  17.  
  18. @logger  
  19. def sum_num( a, b, c ):  
  20.     return a + b + c  


参数检查

[python] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. from itertools import izip  
  2.   
  3. rpc_info = {}  
  4.   
  5. def xmlrpc( in_args = (), out_args = ( type( None ), ) ):  
  6.   
  7.     def _check_types( elements, types ):  
  8.         if len( elements ) != len( types ):  
  9.             raise TypeError( 'argument count is wrong' )  
  10.         typed = enumerate( izip( elements, types ) )  
  11.         for index, couple in typed:  
  12.             arg, type_ = couple  
  13.             if isinstance( arg, type_ ):  
  14.                 continue  
  15.             raise TypeError( 'arg %d should be %s'%( index, type_ ) )  
  16.   
  17.       
  18.     def _xmlrpc( func ):  
  19.         function_name = func.__name__  
  20.         rpc_info[function_name] = ( in_args, out_args )  
  21.           
  22.         def __xmlrpc( *args ):  
  23.             check_args = args[1:]  
  24.             _check_types( check_args, in_args )  
  25.             result = func( *args )  
  26.             if not type( result ) in ( tuple, list ):  
  27.                 check_results = ( result, )  
  28.             else:  
  29.                 check_results = result  
  30.             _check_types( check_results, out_args )  
  31.             return result  
  32.   
  33.         return __xmlrpc  
  34.           
  35.     return _xmlrpc  
  36.   
  37.   
  38.   
  39. class RPCView( object ):  
  40.  
  41.     @xmlrpc( ( int, int ) )  
  42.     def method1( self, int_a, int_b ):  
  43.         print 'recevied %d and %d'%( int_a, int_b )  
  44.  
  45.     @xmlrpc( ( str, ), ( int, ) )  
  46.     def method2( self, info ):  
  47.         print 'received %s'%( info )  
  48.         return 0  
  49.   
  50.       
  51. a = RPCView()  
  52. a.method1( 1221 )  


代理

[python] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. class User( object ):  
  2.     def __init__( self, role ):  
  3.         self.roles = role  
  4.   
  5. class Unauthorized( Exception ):  
  6.     pass  
  7.   
  8.   
  9. def protect( role ):  
  10.     def _protect( function ):  
  11.         def __protect( *args, **kwargs ):  
  12.             user = globals().get( 'user' )  
  13.             if user is None or role not in user.roles:  
  14.                 raise Unauthorized( 'I will not tell you' )  
  15.             return function( *args, **kwargs )  
  16.         return __protect  
  17.     return _protect  
  18.   
  19. tarek = User( ( 'admin''user' ) )  
  20. bill = User( ( 'user', ) )  
  21.   
  22. class MySecrets( object ):  
  23.  
  24.     @protect'admin' )  
  25.     def waffle_recipe( self ):  
  26.         print 'use tons of butter!'  
  27.   
  28.   
  29. these_are = MySecrets()  
  30. #these_are.waffle_recipe()  
  31.   
  32. user = tarek  
  33. these_are.waffle_recipe()  
  34.   
  35. these_are = bill  
  36. these_are.waffle_recipe()  


上下文提供者

[python] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. from threading import RLock  
  2.   
  3. lock = RLock()  
  4.   
  5. def synchronized( function ):  
  6.     def _synchronized( *args, **kwargs ):  
  7.         lock.acquire()  
  8.         try:  
  9.             return function( *args, **kwargs )  
  10.         finally:  
  11.             lock.release()  
  12.     return _synchronized  
  13.  
  14.  
  15. @synchronized  
  16. def thread_safe():  
  17.     pass  
0 0