如下圖,代碼中4個數據,產生了4個頁面,怎么實現只打開一個頁面?可使用單例模式
查詢得知 單例模式實現有5種方法,參照鏈接下:
https://blog.csdn.net/SixStar_FL/article/details/126894579
【資料圖】
1. 使用模塊2. 使用裝飾器3. 使用類4. 基于 __new__ 方法實現5.基于 metaclass 方式實現
這里我們分別使用裝飾器方法和__new__方法,
裝飾器方法代碼如下:
1 # singledriver.py 2 from selenium import webdriver 3 4 def singledriver(cls,*args,**kw): 5 instances = {} 6 def _singledriver(): 7 if cls not in instances: 8 instances[cls] = cls(*args,**kw) 9 print(instances)10 return instances[cls]11 return _singledriver12 13 @singledriver14 class SingleDriver():15 """driver單例"""16 def __init__(self):17 self.driver = webdriver.Firefox()
1 # basepage.py 2 from utils.singledriver import SingleDriver 3 4 class BasePage(MyDriver): 5 """ 6 基類 用作初始化 封裝常用操作 7 """ 8 def __init__(self): 9 """10 初始化driver11 """12 self.driver = SingleDriver().driver13 self.calurl = r"http://cal.apple886.com/"14 self.digit_btn = (By.ID, "simple{}")15 self.open_page()16 self.driver.maximize_window()17 18 if __name__ == "__main__":19 a=BasePage()20 b=BasePage()
分析如下:
1、self.driver = SingleDriver().driver調用SingleDriver()類,因為有裝飾器,直接先到裝飾器singledriver這里,此時cls為空
2、所以cls不在instance中,執行instances[cls] = cls(*args,**kw),給instances字典增加鍵值對,instances結果如下:
{
但是這行我完全看不懂......
3、第二次調用BasePage時,同樣第一步,但此時cls不為空了,所以不會向instance增加新的內容,而是直接返回原來的,也就是沒有再次實例化新的driver
__new__方法代碼如下:
1 # basepage.py 2 class MyDriver(): 3 _instance = None 4 def __new__(cls, *args, **kwargs): 5 if not cls._instance: 6 cls._instance = super(MyDriver, cls).__new__(cls, *args, **kwargs) 7 cls.driver = webdriver.Firefox() 8 return cls._instance 9 10 class BasePage(MyDriver):11 """12 基類 用作初始化 封裝常用操作13 """14 def __init__(self):15 """16 初始化driver17 """18 # self.driver = SingleDriver().driver19 self.calurl = r"http://cal.apple886.com/"20 self.digit_btn = (By.ID, "simple{}")21 self.open_page()22 self.driver.maximize_window()23 24 if __name__ == "__main__":25 a=BasePage()26 b=BasePage()
這個邏輯也一樣,只是把定義driver放在了__new__中了
cls._instance = super(MyDriver, cls).__new__(cls, *args, **kwargs) 這個看不懂......
參考如下:
(117條消息) python裝飾器的理解_自己合計的博客-CSDN博客
(117條消息) Python中cls代表什么意思?_cls參數python_溫柔的行子的博客-CSDN博客
(117條消息) Python類內的cls和self,及單例模式的探究_LSG.haha的博客-CSDN博客
python單例模式&selenium driver實現單例_wx63186321c235c的技術博客_51CTO博客
(117條消息) python中的單例模式_python中單例_程序員老華的博客-CSDN博客
關鍵詞: