用metaclass实现AOP风格的Profiler

以下是一段通过metaclass实现Profiler的Python代码,很简单,功能不多,目的是为了展示Python的meta programming的能力,这种能力,无疑是很实用的,而且可以将AOP的方面(aspect)概念发挥的很好!下面的Profiler类(metaclass)就可以将方法的profiling在不同的类中复用。

class Profiler(type):
    
def __new__(mcl, name, bases, dict):
        
from time import clock
        
from types import FunctionType

        
def timing(func):
            
def wrapper(*args, **kwds):
                start 
= clock()
                value 
= func(*args, **kwds)
                end 
= clock()
                
print func.__name__'takes', (end - start), 'seconds'
                
return value
            
return wrapper

        
for attr, value in dict.iteritems():
            
if isinstance(value, FunctionType):
                dict[attr] 
= timing(value)

        
return super(Profiler, mcl).__new__(mcl, name, bases, dict)

class A(object):
    
__metaclass__ = Profiler

    
def foo(self):
        total 
= 0
        
for i in range(100000):
            total 
= total+1
        
print total

    
def foo2(self):
        
from time import sleep

        total 
= 0
        
for i in range(100000):
            total 
= total+1
            sleep(
0.0001)
        
print total

def main():
    a 
= A()
    a.foo()
    a.foo2()

if __name__ == '__main__':
    main()


此篇为抛砖引玉,希望大家能制作出更多更强的metaclass来,然后不妨与我们分享!:)
posted @ 2006-08-22 10:36  Cavingdeep  阅读(3289)  评论(4编辑  收藏  举报