本文实例讲述了Python单体模式的几种常见实现方法。分享给大家供大家参考,具体如下:
这里python实现的单体模式,参考了:https://stackoverflow.com/questions/1363839/python-singleton-object-instantiation/1363852#1363852
一、修改父类的 __dict__
class Borg:
_shared_state = {}
def __init__(self):
self.__dict__ = self._shared_state
class Singleton(Borg):
def __init__(self, name):
super().__init__()
self.name = name
def __str__(self):
return self.name
x = Singleton('sausage')
print(x)
y = Singleton('eggs')
print(y)
z = Singleton('spam')
print(z)
print(x)
print(y)
注意,这种方法实现的并非真正的单体模式!!
下面几种方法实现的才是真正的单体模式
二、使用元类
先看看这里关于元类的描述:
元类一般用于创建类。
在执行类定义时,解释器必须要知道这个类的正确的元类。解释器会先寻找类属性__metaclass__,如果此属性存在,就将这个属性赋值给此类作为它的元类。如果此属性没有定义,它会向上查找父类中的__metaclass__。如果还没有发现__metaclass__属性,解释器会检查名字为__metaclass__的全局变量,如果它存在,就使用它作为元类。否则, 使用内置的 type 作为此类的元类。
1. 继承 type,使用 __call__
注意__call__的参数
class Singleton(type):
_instance = None
def __call__(self, *args, **kw):
if self._instance is None:
self._instance = super().__call__(*args, **kw)
return self._instance
class MyClass(object):
__metaclass__ = Singleton
print(MyClass())
print(MyClass())
2. 继承 type,使用 __new__
注意__new__的参数
class Singleton(type):
_instance = None
def __new__(cls, name, bases, dct):
if cls._instance is None:
cls._instance = super().__new__(cls, name, bases, dct)
return cls._instance
class MyClass(object):
__metaclass__ = Singleton
print(MyClass())
print(MyClass())
3. 继承 object,使用 __new__
注意__new__的参数
class Singleton(object):
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
class MyClass(object):
__metaclass__ = Singleton
print(MyClass())
print(MyClass())
下面还有一个很巧妙的方法实现单体模式
使用类方法classmethod
class Singleton:
_instance = None
@classmethod
def create(cls):
if cls._instance is None:
cls._instance = cls()
return cls._instance
def __init__(self):
self.x = 5 # or whatever you want to do
sing = Singleton.create()
print(sing.x) # 5
sec = Singleton.create()
print(sec.x) # 5
更多关于Python相关内容可查看本站专题:《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。
Python,单体模式
P70系列延期,华为新旗舰将在下月发布
3月20日消息,近期博主@数码闲聊站 透露,原定三月份发布的华为新旗舰P70系列延期发布,预计4月份上市。
而博主@定焦数码 爆料,华为的P70系列在定位上已经超过了Mate60,成为了重要的旗舰系列之一。它肩负着重返影像领域顶尖的使命。那么这次P70会带来哪些令人惊艳的创新呢?
根据目前爆料的消息来看,华为P70系列将推出三个版本,其中P70和P70 Pro采用了三角形的摄像头模组设计,而P70 Art则采用了与上一代P60 Art相似的不规则形状设计。这样的外观是否好看见仁见智,但辨识度绝对拉满。
更新动态
- 小骆驼-《草原狼2(蓝光CD)》[原抓WAV+CUE]
- 群星《欢迎来到我身边 电影原声专辑》[320K/MP3][105.02MB]
- 群星《欢迎来到我身边 电影原声专辑》[FLAC/分轨][480.9MB]
- 雷婷《梦里蓝天HQⅡ》 2023头版限量编号低速原抓[WAV+CUE][463M]
- 群星《2024好听新歌42》AI调整音效【WAV分轨】
- 王思雨-《思念陪着鸿雁飞》WAV
- 王思雨《喜马拉雅HQ》头版限量编号[WAV+CUE]
- 李健《无时无刻》[WAV+CUE][590M]
- 陈奕迅《酝酿》[WAV分轨][502M]
- 卓依婷《化蝶》2CD[WAV+CUE][1.1G]
- 群星《吉他王(黑胶CD)》[WAV+CUE]
- 齐秦《穿乐(穿越)》[WAV+CUE]
- 发烧珍品《数位CD音响测试-动向效果(九)》【WAV+CUE】
- 邝美云《邝美云精装歌集》[DSF][1.6G]
- 吕方《爱一回伤一回》[WAV+CUE][454M]