一、使用装饰器实现单例
def Singleton(cls):
_instance = {}
def _singleton(*args, **kargs):
if cls not in _instance:
_instance[cls] = cls(*args, **kargs)
return _instance[cls]
return _singleton
@Singleton
class A(object):
a = 1
def __init__(self, x=0):
self.x = x
a1 = A(2)
a2 = A(3)
二、web自动化driver实现单例模式
2.1 编写单例模式的装饰器
singleton.py
#coding:utf-8
#单例模式函数,用来修饰类
def singleton(cls,*args,**kw):
instances = {}
def _singleton():
if cls not in instances:
instances[cls] = cls(*args,**kw)
return instances[cls]
return _singleton
2.2 driver 使用装饰器,实现单例模式
GetSeleniumDriver.py
# -*- coding:utf-8 -*-
from selenium import webdriver
from singleton import singleton
@singleton
class GetSeleniumDriver(object):
def __init__(self):
self.driver = webdriver.Chrome()
2.3 获取driver的实例,就是单例了
class My_task(RES):
def __init__(self):
self.driver=GetSeleniumDriver().driver
def Making_task_Button(self):
Making_task_Button=self.driver.find_element_by_xpath(RES.Making_task_Button_xpth)
return Making_task_Button
def Audit_task_Button(self):
Audit_task_Button=self.driver.find_element_by_xpath(RES.Audit_task_Button_xpth)
return Audit_task_Button