Python 单例模式

Python 单例模式实现方法

1.模块化

# Python 的模块天然就是单例模式
# 模块在第一次被导入时会生成.pyc文件,第二次导入时会直接加载.pyc文件 而不会再次执行模块中的的代码,所以我们可以这样来实现单例模式

# test.py
class A(object):
    def __init__(self, name):
        self.name = name
t = A(treasure)

# test1.py 
from test import t # 这里引入的就是我们单例模式的对象

2.使用装饰器

def test(cls):
    _instance = {}

    def _sing(*args, **kwargs):
        if cls not in _instance:
            _instance[cls] = cls(*args, **kwargs)
        return _instance[cls]
    return _sing

@test
class A(object):

    a = 1

    def __init__(self, x):
        self.x = x

a1 = A(2)
a2 = A(3)

# 打印可知a1, a2 两个对象的内存地址是一样的, 并且a2.x为2

3.基于 _new__方法

import threading
class Singleton(object):
    _instance_lock = threading.Lock()

    def __init__(self):
        pass


    def __new__(cls, *args, **kwargs):
        if not hasattr(Singleton, "_instance"):
            with Singleton._instance_lock:
                if not hasattr(Singleton, "_instance"):
                    Singleton._instance = object.__new__(cls)  
        return Singleton._instance

obj1 = Singleton()
obj2 = Singleton()
print(obj1,obj2)
posted on 2019-02-19 17:53 徐建0304 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/Treasuremy/p/10402664.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值