首页 > 编程语言 > 详细

Python Singleton

时间:2016-01-19 10:43:39      阅读:109      评论:0      收藏:0      [点我收藏+]

Python Singleton

首先声明一个singleton装饰器

#!/usr/bin/env python
# -*- coding: utf-8 -*-


def singleton(cls, *args, **kw):
    instances = {}

    def _singleton():
        if cls not in instances:
            instances[cls] = cls(*args, **kw)
        return instances[cls]

    return _singleton

使用@singleton注解在需要单例的类上标注

#!/usr/bin/env python
# -*- coding: utf-8 -*-


@singleton
class Config:

    def __init__(self):
        pass

    def test(self):
        pass

测试

#!/usr/bin/env python
# -*- coding: utf-8 -*-


config = Config()
config.test()
...

Python Singleton

原文:http://blog.csdn.net/kongxx/article/details/50538927

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!