- 带参数的装饰器
__author__ = ‘similarface‘ import sys import logging import functools logging.basicConfig( stream=sys.stderr, level=logging.DEBUG ) def decorator(config): def concrete_decorator(function): def wrapped( *args, **kw ): return function( *args, ** kw ) return wrapped return concrete_decorator def debug_named(log_name): def concrete_decorator(function): @functools.wraps( function ) def wrapped( *args, **kw ): log= logging.getLogger( log_name ) log.debug( "%s( %r, %r )", function.__name__, args, kw, ) result= function( *args, **kw ) log.debug( "%s = %r", function.__name__, result ) return result return wrapped return concrete_decorator @debug_named( "recursion" ) def ackermann( m, n ): if m == 0: return n+1 elif m > 0 and n == 0: return ackermann( m-1, 1 ) elif m > 0 and n > 0: return ackermann( m-1, ackermann( m, n-1 ) ) print( ackermann(2,4) )
- 类方法装饰器
import sys import logging import functools def audit( method ): @functools.wraps(method) def wrapper( self, *args, **kw ): audit_log= logging.getLogger( ‘audit‘ ) before= repr(self) try: result= method( self, *args, **kw ) after= repr(self) except Exception as e: audit_log.exception( ‘%s before %s\n after %s‘, method.__qualname__, before, after ) raise audit_log.info( ‘%s before %s\nafter %s‘, method.__qualname__, before, after ) return result return wrapper class Person: def __init__( self,*address ): self.address=list(address) @audit def __iadd__( self, addr ): self.address.append(addr) return self def __repr__( self ): address= ", ".join( map(str,self.address) ) return "{__class__.__name__}({addr})".format(__class__=self.__class__, addr=address) logging.basicConfig( stream=sys.stderr, level=logging.DEBUG ) p= Person("北京","上海","天津") p.__iadd__(‘广东‘)
类装饰器
__author__ = ‘similarface‘ import sys import logging logging.basicConfig( stream=sys.stderr, level=logging.DEBUG ) def logged(class_): class_.logger=logging.getLogger(class_.__qualname__) return class_ @logged class Person: def __init__(self,name): self.name=name self.logger.info("Good") def method(self,*args): self.logger.info("method %r",args) @logged class Student(Person): def __init__(self,g): self.name=g self.logger.info("Good") def study(self,*args): self.logger.info("method %r",args) p=Person("similarface") p.method("Nice day") s=Student("similarface") s.method("Nice a day")
时间: 2024-10-03 14:46:02