首页 > 编程语言 >python __new__方法与单例模式

python __new__方法与单例模式

时间:2023-03-17 15:33:32浏览次数:36  
标签:__ Singleton python instance 单例 new def cls

  • 1、new()至少要有一个参数cls,代表当前类,此参数在实例时由python解释器自动识别,
  • 2、new()必须要有返回值,返回实例化出来的实例,这点在自己实现__new__时要特别注意,可以 return父类new出来的实例, 如:return super().new(cls),或者直接return object.new(cls)
  • 3、init有一个参数self,就是这个__new__()方法返回的实例, 可以完成一些其它初始化的动作,init不需要返回值(有返回值就会报错)
  • 4、如果__new__()创建的是当前类的实例,会自动调用__init__()函数, 通过return语句里面调用的__new__(cls)函数的第一个参数是cls来保证是当前类实例, 如果是其他类的类名,那么实际创建返回的就是其他类的实例,其实就不会调用当前类的__init__()函数,也不会调用其他类的__init__()函数。
class A(object):
    def __init__(self):
        print('这是init方法:',self)

    def __new__(cls, *args, **kwargs):
        print('这是cls类本身的ID:',id(cls))
        print('这是new方法:',object.__new__(cls))
        # print('这是new方法:',super().__new__(cls))  # 跟上面那句本质一样,都是调用父类的new方法
        return object.__new__(cls)

A()
print('这是A类的ID:',id(A))

'''输出结果如下:
这是cls类本身的ID: 2790056212288
这是new方法: <__main__.A object at 0x000002899CB281C0>
这是init方法: <__main__.A object at 0x000002899CB281C0>
这是A类的ID: 2790056212288
'''

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

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

事实上,类似 AppConfig 这样的类,我们希望在程序运行期间只存在一个实例对象。

实现单例模式:
  • 使用模块
  • 使用装饰器
  • 使用类
  • 基于 new 方法实现
  • 基于 metaclass 方式实现
1、使用模块

Python 的模块就是天然的单例模式

2、使用装饰器
def singleton(cls):
    _instance = dict()

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


@singleton
class A(object):
    a = 1

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


a1 = A(2)
print(a1)
a2 = A(3)
print(a2)
print(a1 is a2)
3、使用类
  • 多线程单例模式
import time
import threading
 
 
class Singleton(object):
    _instance_lock = threading.Lock()
 
    def __init__(self):
        time.sleep(1)
 
    @classmethod
    def instance(cls, *args, **kwargs):
        if not hasattr(Singleton, "_instance"):
            with Singleton._instance_lock:
                if not hasattr(Singleton, "_instance"):
                    Singleton._instance = Singleton(*args, **kwargs)
        return Singleton._instance
 
 
def task(arg):
    obj = Singleton.instance()
    print(obj)
    
    
for i in range(10):
    t = threading.Thread(target=task,args=[i,])
    t.start()
    
    
time.sleep(20)
obj = Singleton.instance()
print(obj)
4、基于 new 方法实现
class Singleton(object):
    _instance = None

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

        return cls._instance
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)
 
def task(arg):
    obj = Singleton()
    print(obj)
 
for i in range(10):
    t = threading.Thread(target=task,args=[i,])
    t.start()
基于 metaclass 方式实现
import threading
 
class SingletonType(type):
    _instance_lock = threading.Lock()
    def __call__(cls, *args, **kwargs):
        if not hasattr(cls, "_instance"):
            with SingletonType._instance_lock:
                if not hasattr(cls, "_instance"):
                    cls._instance = super(SingletonType,cls).__call__(*args, **kwargs)
        return cls._instance
 
class Foo(metaclass=SingletonType):
    def __init__(self,name):
        self.name = name
 
 
obj1 = Foo('name')
obj2 = Foo('name')
print(obj1,obj2)

标签:__,Singleton,python,instance,单例,new,def,cls
From: https://www.cnblogs.com/wyh0923/p/17226986.html

相关文章

  • 【Android 逆向】【攻防世界】ill-intentions
    1.apk安装到手机,啥输入框都没有2.apk拖入到jadx中看看publicclassMainActivityextendsActivity{@Override//android.app.ActivitypublicvoidonCr......
  • 均值方差合并
    公式:参考:linkA数组包含m个元素,均值为mean1,方差为Var1,B数组包含n个元素,均值为mean2,方差为Var2\[mean=(n\cdotmean1+m\cdotmean2)/(m+n)\\var=(n\cdot......
  • bs4介绍,遍历文档树、bs4搜索文档树、css选择器、selenium基本使用、无界面浏览器、sel
    目录0bs4介绍,遍历文档树0.1bs4的遍历文档树1bs4搜索文档树1.1find的其他参数2css选择器3selenium基本使用4无界面浏览器4.1模拟登录百度5selenium其它用法5.0查......
  • Canal学习
    在mysql创建cancel用户#使用CREATEUSER创建一个用户,用户名是canal,密码是canal,主机名是localhost。SQL语句和执行过程如下。createuser'canal'@'%'identified......
  • Web漏洞-CSRF及SSRF漏洞案例讲解
      CSRF漏洞解释,原理CSRF:跨站请求伪造,是一种网络的攻击方式(核心:伪造请求)黑客利用某网站用户的登陆状态,然后伪造请求的链接,造成对登录态用户的修改等各种危险操作被......
  • docker 运行filebeat收集日志
    1.简介beats首先filebeat是Beats中的一员。Beats在是一个轻量级日志采集器,其实Beats家族有6个成员,早期的ELK架构中使用Logstash收集、解析日志,但是Logstash对内存、......
  • 1个案例读懂——游戏产品如何用 A/B 测试做增长
    更多技术交流、求职机会,欢迎关注字节跳动数据平台微信公众号,回复【1】进入官方交流群 随着国内游戏用户数量趋于饱和,中国游戏产业也从高速成长期逐渐转型,市场成熟度提......
  • 中英文章11 低成本设备可以在任何地方测量空气污染
     https://news.mit.edu/2023/low-cost-device-can-measure-air-pollution-anywhere-0316 Low-costdevicecanmeasureairpollutionanywhere低成本设备可以在任何......
  • 设备检测,系统无法识别。没有打开前端口的音频。
    处理方法:(1)打开开始--控制面板-选择"声音、语音和音频设备"--“Realtek高清晰音频配置”;(2)进入"Realtek高清晰音频配置"界面,选择切换到顶部的"音频I/O"选项卡,并点击......
  • 2023/3/16每日随笔
    今天主要完成了AndroidStudio开发的项目首尾工作,将记事本的添加删除修改的操作进行了完善,加入了闹钟功能,可设置闹铃来提示,同时也进行了打卡功能的完成,但是对于切换角色进......