python单例模式

时间:2020-07-06 01:37:14   收藏:0   阅读:75

单例模式(Singleton Pattern)是一种常用的软件设计模式,该模式的主要目的是确保某一个类只有一个实例存在。当你希望在整个系统中,某个类只能出现一个实例时,单例对象就能派上用场。

import time
class A():
    instance=None
    def __init__(self):
        pass
    def __new__(cls, *args, **kwargs):
        if cls.instance is None:
            cls.instance=super().__new__(cls)
        return cls.instance
    def setup(self):
        print("Cur time:",time.time())
if __name__ == __main__:
    a=A()
    b=A()
    print(id(a),id(b))
    a.setup()
    b.setup()
2394818100424 2394818100424
Cur time: 1593963540.9315283
Cur time: 1593963540.9315283

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!