python单例模式

Python单例模式的好处主要有以下几点:

  1. 节省资源:单例模式可以确保一个类只有一个实例,这样可以避免在多个地方创建相同的对象,从而节省内存和计算资源。

  2. 保证数据一致性:在多线程环境下,单例模式可以确保全局变量只被初始化一次,避免了多线程同时修改数据导致的数据不一致问题。

  3. 方便控制访问:单例模式可以提供一个全局访问点,使得其他对象只能通过这个访问点来访问该实例,方便对实例的访问控制。

Python单例模式的实现示例:

class Singleton:
    # 使用类属性_instance来存储唯一的实例
    _instance = None

    def __new__(cls, *args, **kwargs):
        # 如果_instance为None,说明还没有创建实例,则调用父类的__new__方法创建一个实例
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        # 如果_instance已经存在,说明已经创建过实例,直接返回该实例
        return cls._instance

    def __init__(self):
        # 初始化实例时可以添加一些自定义操作
        pass

# 测试单例模式
singleton1 = Singleton()
singleton2 = Singleton()

print(singleton1 is singleton2)  # 输出True,说明singleton1和singleton2是同一个实例

 

Python类的单例模式实现。如果类DriverConfigure的实例不存在,那么就创建一个新的实例。这个新的实例会加载一个配置文件,并使用这个配置文件来初始化webdriver的远程驱动。

# driver_configure.py
# coding:utf-8
__author__ = 'may'
'''
description:driver配置

'''
import os.path
from appium import webdriver
from config import operator_yaml
from config.all_path import project_path


class DriverConfigure(object):
_instance = None
def __new__(cls, *args, **kw): """ 使用单例模式将类型设置为运行时只有一个实例, 在其他python类中使用基类时, 可以创建多个对象,保证所有的对象都基于一个浏览 :param args: :param kw: :return: hasattr()函数功能用来检测对象object中是否含有名为**的属性, 如果有就返回True,没有就返回False """ if not hasattr(cls, '_instance'): orig = super(DriverConfigure, cls) path = os.path.join(project_path, "config\config.yaml") data = operator_yaml.readconfigyaml(path) # 远程控制,通过appium可设置;若是真机,直接填写http://localhost:4723/wd/hub 或者http://127.0.0.1:4723/wd/hub即可 cls._instance = orig.__new__(cls) # 发送指令到appium server cls._instance.driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", data["desired_caps"]) return cls._instance class DriverClinet(DriverConfigure): def get_driver(self): return self.driver

注释:

# 检查类是否已经有'_instance'属性,如果没有,则进入下面的代码块
if not hasattr(cls, '_instance'):
    # 调用父类的__new__方法创建一个新的对象,并将其赋值给orig
    orig = super(DriverConfigure, cls)
    # 构造配置文件的路径,配置文件位于项目路径下的config文件夹中,文件名为config.yaml
    path = os.path.join(project_path, "config\config.yaml")
    # 使用operator_yaml库的readconfigyaml方法读取配置文件的内容,返回的结果赋值给data
    data = operator_yaml.readconfigyaml(path)
    
    # 通过调用父类的__new__方法创建一个新的实例,并将其赋值给cls._instance
    cls._instance = orig.__new__(cls)
    
    # 使用从配置文件中读取的数据初始化webdriver的远程驱动,驱动的地址为"http://127.0.0.1:4723/wd/hub"
    cls._instance.driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", data["desired_caps"])
# 返回cls._instance,如果已经存在就直接返回,否则就创建一个新的实例并返回
return cls._instance

 

posted @ 2023-10-06 19:18  yimu-yimu  阅读(37)  评论(0编辑  收藏  举报