Python 实现单例模式

本文介绍了单例模式的两种实现方法:一种是通过重写__new__方法;另一种是利用类属性结合get函数。这两种方法虽然都能实现单例模式,但它们在实例变量的处理上存在差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、借助 __new__ 来实现

class Singleton(object):
    def __new__(cls, *args, **kw):
        if not hasattr(cls, '_instance'):
            orig = super(Singleton, cls)
            cls._instance = orig.__new__(cls, *args, **kw)
        return cls._instance

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

a = Singleton(1)
b = Singleton(2)
print a==b
print a.x, b.x
#True
#2 2

二、借助类属性与get函数

class Myclass(object):
    _sigle_cls = None
    def __init__(self, x):
        self.x = x
    @classmethod
    def get_cls(cls, *args, **argk):
        if not cls._sigle_cls:
            cls._sigle_cls = cls(*args, **argk)
        return cls._sigle_cls

a = Myclass.get_cls(1)
print a.x
b = Myclass.get_cls(2)
print "a.x:",a.x, "b.x", b.x
#a.x: 1 b.x 1

这两种方式还是有区别的,不知道看了此博文的同学发现了没?


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值