Python Singleton

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python Singleton相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

常用python日期日志获取内容循环的代码片段

以singleton(python)更新属性

python 有用的Python代码片段

python singleton design pattern super()

Python 向 Postman 请求代码片段

python [代码片段]一些有趣的代码#sort