Python单例

2019-07-11  本文已影响0人  Aresx

Python单例

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>
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,如对知识点理解有误还请指正。欢迎补充不足之处,看到后我会及时补充进文章中。

上一篇 下一篇

猜你喜欢

热点阅读