1、定义:
单例类只能有一个实例。
单例类必须自己创建自己的唯一实例。
单例类必须给所有其他对象提供这一实例。
2、实现:
1)new:
#!/usr/bin/python
# Write Python 3 code in this online editor and run it.
class Single:
    
    ins = None
    
    def __new__(cls):
        if cls.ins is None:
            ins = super().__new__(cls)
        return cls.ins
    
s1 = Single()
s2 = Single()
print(id(s1))
print(id(s2))

image.png
2)@classmethod:
#!/usr/bin/python
# Write Python 3 code in this online editor and run it.
print("Hello, World!");
class Single:
    
    ins = None
    
    @classmethod
    def getinstance(cls):
        if cls.ins is None:
            cls.ins = super().__new__(cls)
        return cls.ins
    
    
single = Single.getinstance()
single1 = Single.getinstance()
print(id(single))
print(id(single1))
[图片上传失败...(image-17d15b-1732606516659)]
3)通过装饰器
#!/usr/bin/python
# Write Python 3 code in this online editor and run it.
print("Hello, World!");
def outter(func):
    ins = {}
    def inner():
        if func not in ins:
            ins[func] = func()
        return ins[func]
    return inner
@outter
class Single:
    pass
s1 = Single()
s2 = Single()
print(id(s1))
print(id(s2))

image.png
- 通过导入模块时实现
 from test import Test
模块第一次导入时会加载到内存空间,第二次或以后再导入时,则会直接引用
5)通过元类实现
#!/usr/bin/python
# Write Python 3 code in this online editor and run it.
print("Hello, World!");
class Single(object):
    ins = ""
    def __new__(cls):
        if not hasattr(Single,'ins'):
            cls.ins = object().__new__(cls)
        return cls.ins
            
s1 = Single()
s2 = Single()
print(id(s1))
print(id(s2))

image.png