• 单例模式


    class MySQL:
    __sign = None
    def __init__(self):
    self.host = "127.0.0.1"
    self.port = 3306

    @classmethod
    def signleton(cls):
    if not cls.__sign:
    obj = cls()
    cls.__sign = obj
    return cls.__sign

    def conn(self):
    pass

    m1 = MySQL.signleton()
    m2 = MySQL.signleton()
    print(m1 is m2,"1")

    #但是这样必须调用类方法sighlenton来实例化。

    """
    通过元类实现单例模式
    """


    class MySQLmeta(type):
    __sign = None

    def __call__(self, *args, **kwargs):
    if not MySQLmeta.__sign:
    obj = object.__new__(self)
    self.__init__(obj, *args, **kwargs)
    MySQLmeta.__sign = obj
    return MySQLmeta.__sign


    class MySQL(metaclass=MySQLmeta):
    def __init__(self):
    self.host = "127.0.0.1"
    self.port = 3306

    def conn(self):
    pass

    m1 = MySQL()
    m2 = MySQL()
    print(m1 is m2,"2")


    class MySQLmeta(type):

    def __init__(self, class_name, class_bases, class_dict):
    super(MySQLmeta, self).__init__(class_name, class_bases, class_dict)
    self.__sign = None

    def __call__(self, *args, **kwargs):
    if not self.__sign:
    obj = object.__new__(self)
    self.__init__(obj, *args, **kwargs)
    self.__sign = obj
    return self.__sign


    class MySQL(metaclass=MySQLmeta):
    def __init__(self):
    self.host = "127.0.0.1"
    self.port = 3306

    def conn(self):
    pass

    m1 = MySQL()
    m2 = MySQL()
    print(m1 is m2,"3")

    """
    通过new方法实现单例模式
    """

    class MySQL(metaclass=MySQLmeta):
    __sign = None

    def __new__(cls, *args, **kwargs):
    if not cls.__sign:
    obj = super().__new__(cls, *args, **kwargs)
    cls.__sign = obj
    return cls.__sign

    def __init__(self):
    self.host = "127.0.0.1"
    self.port = 3306

    def conn(self):
    pass

    m1 = MySQL()
    m2 = MySQL()
    print(m1 is m2,"4")
  • 相关阅读:
    逐个图片保存成视频
    GitHub搜索
    用cmd运行jmeter并生成报告
    jmeter-json提取器提取的内容含”引号
    jmeter-JSON提取器
    git 上传Access denied解决方法
    Jmeter鲜为人知的jsonpath用法
    selenium 安装流程、下载chromedriver
    jmeter-抓取数据库数据,循环请求1000次(变量嵌套变量)
    jmeter—获取当前时间(年、月、日),往前/往后n天
  • 原文地址:https://www.cnblogs.com/walle-zhao/p/10775964.html
Copyright © 2020-2023  润新知