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): 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