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

推荐订阅源

人人都是产品经理
人人都是产品经理
Blog — PlanetScale
Blog — PlanetScale
MyScale Blog
MyScale Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
WordPress大学
WordPress大学
Vercel News
Vercel News
D
Docker
博客园 - 聂微东
T
Tailwind CSS Blog
aimingoo的专栏
aimingoo的专栏
云风的 BLOG
云风的 BLOG
D
DataBreaches.Net
B
Blog RSS Feed
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - Franky
Microsoft Security Blog
Microsoft Security Blog
美团技术团队
F
Fortinet All Blogs
MongoDB | Blog
MongoDB | Blog
T
The Blog of Author Tim Ferriss
GbyAI
GbyAI
N
Netflix TechBlog - Medium
G
Google Developers Blog
腾讯CDC

博客园 - Cavingdeep

用metaclass实现AOP风格的Profiler 初试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
Singleton implementation using metaclass
Cavingdeep · 2006-08-22 · via 博客园 - Cavingdeep

这里是一段Python代码,展示了如何利用metaclass来实现一个通用的Singleton,这使任何一个class都可以简单的复用这一行为:

class Singleton(type):
    
def __call__(cls, *args):
        
if not hasattr(cls, 'instance'):
            cls.instance 
= super(Singleton, cls).__call__(*args)
        
return cls.instanceclass Cache(object):
    
__metaclass__ = Singletondef main():
    cache 
= Cache()
    cache.data1 
= 1
    
print 'data1 == %s' % cache.data1

    cache2 

= Cache()
    cache2.data1 
= cache2.data1 + 1
    
print 'data1 is increased by 1.'
    
print 'data1 == %s' % cache.data1if __name__ == '__main__':
    main()

这是一个简单的meta programming的应用展示,展示了metaclass所蕴涵的强大的能力,只要想得到,metaclass可以实现各种各样用通常手法做不到或很难实现的功能。:D