首页 > 编程语言 >python实现单例的几种方式

python实现单例的几种方式

时间:2023-08-04 09:56:11浏览次数:40  
标签:__ Singleton python 几种 instance 单例 ._ cls

单例模式

单例模式(Singleton Pattern)是一种常用的软件设计模式,该模式的主要目的是确保某一个类只有一个实例存在。当你希望在整个系统中,某个类只能出现一个实例时,单例对象就能派上用场。

比如,某个服务器程序的配置信息存放在一个文件中,客户端通过一个 AppConfig 的类来读取配置文件的信息。如果在程序运行期间,有很多地方都需要使用配置文件的内容,也就是说,很多地方都需要创建 AppConfig 对象的实例,这就导致系统中存在多个 AppConfig 的实例对象,而这样会严重浪费内存资源,尤其是在配置文件内容很多的情况下。事实上,类似 AppConfig 这样的类,我们希望在程序运行期间只存在一个实例对象。

实现单例模式的几种方式

1.使用模块

其实,Python 的模块就是天然的单例模式,因为模块在第一次导入时,会生成 .pyc 文件,当第二次导入时,就会直接加载 .pyc 文件,而不会再次执行模块代码。因此,我们只需把相关的函数和数据定义在一个模块中,就可以获得一个单例对象了。如果我们真的想要一个单例类,可以考虑这样做:

mysingleton.py

class Singleton(object):
    def foo(self):
        pass
singleton = Singleton()

将上面的代码保存在文件 mysingleton.py 中,要使用时,直接在其他文件中导入此文件中的对象,这个对象即是单例模式的对象

from a import singleton

2.使用装饰器

def Singleton(cls):
    instance = None

    def _singleton(*args, **kargs):
        nonlocal instance
        if not instance:
            instance = cls(*args, **kargs)
        return instance

    return _singleton


@Singleton
class A(object):
    def __init__(self, x=0):
        self.x = x


a1 = A(2)
a2 = A(3)
print(a1.x)
print(a2.x)

print(a1 is a2)

3.使用类方法

class Singleton(object):
    _instance=None
    def __init__(self):
        pass
    @classmethod
    def instance(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance=cls(*args, **kwargs)
        return cls._instance

a1=Singleton.instance()
a2=Singleton().instance()

print(a1 is a2)

4.基于new方法实现

class Singleton(object):
    _instance=None
    def __init__(self):
        pass


    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = object.__new__(cls)
        return cls._instance

obj1 = Singleton()
obj2 = Singleton()
print(obj1 is obj2)

5.基于metaclass方式实现

class SingletonType(type):
    _instance=None
    def __call__(cls, *args, **kwargs):
        if not cls._instance:
            # cls._instance = super().__call__(*args, **kwargs)
            cls._instance = object.__new__(cls)
            cls._instance.__init__(*args, **kwargs)
        return cls._instance

class Foo(metaclass=SingletonType):
    def __init__(self,name):
        self.name = name


obj1 = Foo('name')
obj2 = Foo('name')
print(obj1.name)
print(obj1 is obj2)

标签:__,Singleton,python,几种,instance,单例,._,cls
From: https://www.cnblogs.com/liuqingzheng/p/17605093.html

相关文章

  • ubuntu 默认python版本切换
    Ubuntu下完美切换Python版,即设置系统默认的python版本(亲测有效)_ubuntu切换python版本_关彼得的博客-CSDN博客 sudosuupdate-alternatives--listpythonupdate-alternatives:error:noalternativesforpythonupdate-alternatives--install/usr/bin/pythonpytho......
  • 盘点一个初学者Python库安装的问题(Mac系统)(下篇
    大家好,我是皮皮。一、前言前几天在Python私教群【Emma】问了一个Python库安装的基础问题,一起来看看吧。上一篇文章讲到【Emma】的远程环境不给力,需要继续本地指导。二、实现过程针对导包失败的问题,这里【狂吃山楂片】给了一个解决方法,如下图所示:右下角可以设置环境,你点一下,......
  • python + mysql
    1.连接mysql数据库,基本数据查询流程#1.连接conn=pymysql.connect(host='127.0.0.1',port=3306,user='root',password='',db='db8',charset='utf8')#2.创建游标cursor=conn.cursor()#注意%s需要加引号sql="select*fromu......
  • 【备考实战】计算机二级Python刷题【一】
    时间报名时间:2023-8-31考试时间:2023-9-23第1题计算机完成一条指令所花费的时间称为一个A.执行时序B.存取周期C.执行速度D.指令周期参考解析参考解析:D[解析]一般把计算机完成一条指令所花费的时间称为-一个指令周期。指令周期越短,指令执行就越快。本题答案为D选项......
  • Python用RNN神经网络:LSTM、GRU、回归和ARIMA对COVID19新冠疫情人数时间序列预测|附代
    全文下载链接: http://tecdat.cn/?p=27042最近我们被客户要求撰写关于新冠疫情的研究报告,包括一些图形和统计输出。在本文中,该数据根据世界各国提供的新病例数据提供。获取时间序列数据  df=pd.read_csv("C://global.csv")探索数据此表中的数据以累积的形式呈现,为了......
  • vscode snnipet of python
    {//Placeyoursnippetsforpythonhere.Eachsnippetisdefinedunderasnippetnameandhasaprefix,bodyand//description.Theprefixiswhatisusedtotriggerthesnippetandthebodywillbeexpandedandinserted.Possiblevariablesare://$1,......
  • Python 优化第一步: 性能分析实践 使用cporfile+gprof2dot可视化
    拿来主义:python-mcProfile-oprofile.pstatsto_profile.pygprof2dot-fpstatsprofile.pstats|dot-Tpng-oclick.png然后顺着浅色线条优化就OK了。 windows下:google下graphviz-2.38.msi,然后安装。dot命令需要。gitclone https://github.com/jrfonseca/gprof2dot.git......
  • python 闭包变量不允许write,要使用nonlocal
     以下是一段简单的闭包代码示例:deffoo():m=3n=5defbar():a=4returnm+n+areturnbar>>>bar=foo()>>>bar()12是可以的!但是:deffoo():m=3n=5defbar():a=4m+=1#不可以!!!return......
  • python 代码混淆工具汇总
    pyminifierPyminifierisaPythoncodeminifier,obfuscator,andcompressor.NoteForthelatest,completedocumentation:http://liftoff.github.io/pyminifier/Forthelatestcode:https://github.com/liftoff/pyminifierOverviewWhenyouinstallpyminifierit......
  • Python安装与配置
    一、Windows下安装Python3。官网地址:https://www.python.org/下载地址:https://www.python.org/ftp/python/3.6.4/python-3.6.4-amd64.exe二、安装1、为了不去设置环境变量,我选择Customizeinstallation安装,并且勾选AddPython3.6toPATH。   2、选择安装路径,我安装......