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

推荐订阅源

Google DeepMind News
Google DeepMind News
Stack Overflow Blog
Stack Overflow Blog
Hugging Face - Blog
Hugging Face - Blog
博客园_首页
T
The Blog of Author Tim Ferriss
博客园 - 叶小钗
N
Netflix TechBlog - Medium
腾讯CDC
C
Check Point Blog
P
Proofpoint News Feed
Engineering at Meta
Engineering at Meta
GbyAI
GbyAI
S
SegmentFault 最新的问题
F
Fortinet All Blogs
美团技术团队
U
Unit 42
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - 司徒正美
F
Full Disclosure
Recorded Future
Recorded Future
D
DataBreaches.Net
博客园 - 【当耐特】
Martin Fowler
Martin Fowler
J
Java Code Geeks
I
InfoQ
Y
Y Combinator Blog
A
About on SuperTechFans
AI
AI
爱范儿
爱范儿
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Forbes - Security
Forbes - Security
W
WeLiveSecurity
M
MIT News - Artificial intelligence
雷峰网
雷峰网
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Simon Willison's Weblog
Simon Willison's Weblog
Schneier on Security
Schneier on Security
The GitHub Blog
The GitHub Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
aimingoo的专栏
aimingoo的专栏
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
G
GRAHAM CLULEY
Know Your Adversary
Know Your Adversary
Latest news
Latest news
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
D
Docker
Recent Commits to openclaw:main
Recent Commits to openclaw:main
量子位
V2EX - 技术
V2EX - 技术
Project Zero
Project Zero

博客园 - 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