本文主要是介绍python 装饰器与AOP,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
缓存
from functools import wrapslineseq = '==' * 20def memo( func ):cache = {}@wraps( func )def wrapper( *args ):result = cache.get( args )if result is None:result = func( *args )cache[args] = resultreturn resultreturn wrapper@memo
def fib( n ):if n < 2:return nreturn fib( n - 1 ) + fib( n - 2 )print fib( 10 )
注册函数信息
import timedef logger( func ):@wraps( func )def deco( *args, **kwargs ):start_time = time.time()result = func( *args, **kwargs )end_time = time.time()print 'function = {0}'.format( func.__name__ )print 'arguments = {0}{1}'.format( args, kwargs )print 'return = {0}'.format( result )print 'time = %.6f sec'%( start_time - end_time )return resultreturn deco@logger
def sum_num( a, b, c ):return a + b + c
参数检查
from itertools import iziprpc_info = {}def xmlrpc( in_args = (), out_args = ( type( None ), ) ):def _check_types( elements, types ):if len( elements ) != len( types ):raise TypeError( 'argument count is wrong' )typed = enumerate( izip( elements, types ) )for index, couple in typed:arg, type_ = coupleif isinstance( arg, type_ ):continueraise TypeError( 'arg %d should be %s'%( index, type_ ) )def _xmlrpc( func ):function_name = func.__name__rpc_info[function_name] = ( in_args, out_args )def __xmlrpc( *args ):check_args = args[1:]_check_types( check_args, in_args )result = func( *args )if not type( result ) in ( tuple, list ):check_results = ( result, )else:check_results = result_check_types( check_results, out_args )return resultreturn __xmlrpcreturn _xmlrpcclass RPCView( object ):@xmlrpc( ( int, int ) )def method1( self, int_a, int_b ):print 'recevied %d and %d'%( int_a, int_b )@xmlrpc( ( str, ), ( int, ) )def method2( self, info ):print 'received %s'%( info )return 0a = RPCView()
a.method1( 12, 21 )
代理
class User( object ):def __init__( self, role ):self.roles = roleclass Unauthorized( Exception ):passdef protect( role ):def _protect( function ):def __protect( *args, **kwargs ):user = globals().get( 'user' )if user is None or role not in user.roles:raise Unauthorized( 'I will not tell you' )return function( *args, **kwargs )return __protectreturn _protecttarek = User( ( 'admin', 'user' ) )
bill = User( ( 'user', ) )class MySecrets( object ):@protect( 'admin' )def waffle_recipe( self ):print 'use tons of butter!'these_are = MySecrets()
#these_are.waffle_recipe()user = tarek
these_are.waffle_recipe()these_are = bill
these_are.waffle_recipe()
上下文提供者
from threading import RLocklock = RLock()def synchronized( function ):def _synchronized( *args, **kwargs ):lock.acquire()try:return function( *args, **kwargs )finally:lock.release()return _synchronized@synchronized
def thread_safe():pass
这篇关于python 装饰器与AOP的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!