Python的functools模組, 提供了3個有趣函數, partial, update_wrapper 和wraps 。
partial函數,它可以重新綁定函數的選擇性參數,產生一個callable的partial對象。
update_wrapper函數,把被封裝函數的__name__、__module__、__doc__和 __dict__都複製到封裝函數去。
wraps函數,對update_wrapper更進一步封裝。
可以利用wraps函數,實現簡單的方法攔截機制,來實現自己的PerformanceCountCallHandler,
具體實現:
#-*- coding: UTF-8 -*-#-------------------------------------------------------------------------------# Name: 模組2# Purpose:## Author: ankier## Created: 22-12-2012# Copyright: (c) Ankier 2012# Licence: <2012~2020>#-------------------------------------------------------------------------------import timefrom functools import wraps_Cache ={}def PerformanceCountCallHandler(): def _PerformanceCountCallHandler(fun): @wraps(fun) def wrap(args, kw): glos = fun.func_globals package = glos['__package__'] model = glos['__name__'] methodName = fun.func_name timeStart = time.time() result = fun(args, kw) timeEnd = time.time() print 'package:',package,' , model:', model, ' , methodName:',methodName,'. ', timeEnd - timeStart, 's' return result return wrap return _PerformanceCountCallHandler
import timefrom cacheCallHandler import CacheCallHandlerfrom performanceCountCallHandler import PerformanceCountCallHandler@CacheCallHandler()@PerformanceCountCallHandler()def Sum(xx , yy ): sum = xx + yy print '------sum----- ' time.sleep(10) return sumprint Sum(4, 5)print Sum(4, 5)
import timefrom cacheCallHandler import CacheCallHandlerfrom performanceCountCallHandler import PerformanceCountCallHandler@PerformanceCountCallHandler()@CacheCallHandler()def Sum(xx , yy ): sum = xx + yy print '------sum----- ' time.sleep(10) return sumprint Sum(4, 5)print Sum(4, 5)
運行結果
------sum----- file = /root/workspace/study/source/cacheCallHandler/cacheCallHandler.py , method = Sum , performance count (s): 10.0078930855 s9file = /root/workspace/study/source/cacheCallHandler/cacheCallHandler.py , method = Sum , performance count (s): 6.8187713623e-05 s9