美文网首页
Python单例

Python单例

作者: Aresx | 来源:发表于2019-07-11 17:54 被阅读0次

Python单例

  • 一般单例,利用内置函数def __new__(cls, *args, **kwargs)实现单例模式。
class Singleton:
    __instance = None

    def __new__(cls, *args, **kwargs):
        if cls.__instance is None:
            cls.__instance = super().__new__(cls)
        return cls.__instance


for i in range(5):
    print(Singleton())

输出:

<__main__.Singleton object at 0x000002184F47D198>
<__main__.Singleton object at 0x000002184F47D198>
<__main__.Singleton object at 0x000002184F47D198>
<__main__.Singleton object at 0x000002184F47D198>
<__main__.Singleton object at 0x000002184F47D198>
  • 考虑到多线程,利用with锁对上面代码优化
import threading


class SingletonThread:
    __instance = None
    __instance_lock = threading.Lock()

    def __new__(cls, *args, **kwargs):
        with cls.__instance_lock:
            if cls.__instance is None:
                cls.__instance = super().__new__(cls)
            return cls.__instance


def test():
    print("线程ident:%d   线程名:%s" % (threading.current_thread().ident, threading.current_thread().name))
    print("变量地址:%s" % SingletonThread())


for i in range(5):
    t = threading.Thread(target=test, name="thread" + str(i))
    t.start()

输出:

线程ident:17644   线程名:thread0
变量地址:<__main__.SingletonThread object at 0x0000025EF11729B0>
线程ident:10740   线程名:thread1
变量地址:<__main__.SingletonThread object at 0x0000025EF11729B0>
线程ident:18824   线程名:thread2
变量地址:<__main__.SingletonThread object at 0x0000025EF11729B0>
线程ident:19268   线程名:thread3
变量地址:<__main__.SingletonThread object at 0x0000025EF11729B0>
线程ident:6712   线程名:thread4
变量地址:<__main__.SingletonThread object at 0x0000025EF11729B0>

初学python,如对知识点理解有误还请指正。欢迎补充不足之处,看到后我会及时补充进文章中。

相关文章

网友评论

      本文标题:Python单例

      本文链接:https://www.haomeiwen.com/subject/istjkctx.html