惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

A
About on SuperTechFans
G
Google Developers Blog
L
LangChain Blog
aimingoo的专栏
aimingoo的专栏
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
云风的 BLOG
云风的 BLOG
小众软件
小众软件
月光博客
月光博客
Recent Announcements
Recent Announcements
人人都是产品经理
人人都是产品经理
P
Proofpoint News Feed
博客园 - 聂微东
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
雷峰网
雷峰网
The Cloudflare Blog
博客园_首页
美团技术团队
大猫的无限游戏
大猫的无限游戏
B
Blog
IT之家
IT之家
Jina AI
Jina AI
H
Hackread – Cybersecurity News, Data Breaches, AI and More
C
Check Point Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知

博客园 - Cavingdeep

Singleton implementation using metaclass 初试IronPython与.NET的集成 Refactoring as a way to improve the existing design 用metaclass来实现AOP 不该用Generics实现Abstract Factory的理由 新兴XML处理方法VTD-XML介绍 Performance Tips I DCG 2.0.72 (Beta1) 发布了 NUnit发布2.2.3兼容.NET 2.0 RTM 如果你想拥有一个可嵌入式模板引擎…… 改进ASP语法打造更高效的模板语言II 改进ASP语法打造更高效的模板语言 XML的特征以及一些用途 Release of DbHelper 1.2.1 深入XML系列技术 DbHelper at Tigris SQLite系列 集合的初始容量与性能 DbHelper basic usage
用metaclass实现AOP风格的Profiler
Cavingdeep · 2006-08-22 · via 博客园 - Cavingdeep

以下是一段通过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 FunctionTypedef timing(func):
            
def wrapper(*args, **kwds):
                start 
= clock()
                value 
= func(*args, **kwds)
                end 
= clock()
                
print func.__name__'takes', (end - start), 'seconds'
                
return value
            
return wrapperfor 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__ = Profilerdef foo(self):
        total 
= 0
        
for i in range(100000):
            total 
= total+1
        
print totaldef foo2(self):
        
from time import sleep

        total 

= 0
        
for i in range(100000):
            total 
= total+1
            sleep(
0.0001)
        
print totaldef main():
    a 
= A()
    a.foo()
    a.foo2()
if __name__ == '__main__':
    main()

此篇为抛砖引玉,希望大家能制作出更多更强的metaclass来,然后不妨与我们分享!:)