Selenium 中的单例实现 [Python]

Singleton realization in Selenium [Python]

我正在尝试将单例模式用于带有 Selenium 和 Behave 的项目,但它无法正常工作 - 对象总是在 @then 装饰器下第二次创建。我想我在 new 方法中犯了一些错误,但无法真正看到哪里。

class WebDriver:
    singleton_instance = None
    driver = None

    def __init__(self):
       self.driver = webdriver.Chrome("C:\webdriver\chromedriver.exe")



    def __new__(cls):
        if not hasattr(cls, 'instance'):
            cls.singleton_instance = super(WebDriver, cls).__new__(cls)
        return cls.singleton_instance

@given ("website '{url}'")
def website_opener(context,url):
    driver = WebDriver()
    print(driver.singleton_instance)

@then("push button with text '{text}'")
def button_pusher(context,text):
   driver = WebDriver() #another object of WebDriver() is created
   print(driver.singleton_instance)

   WebDriverWait(driver,120).until(
     EC.element_to_be_clickable((By.XPATH,'//*[contains(text(), "%s")]' % text))
   )

context.browser.quit()

您对 hasattr(cls,'instance') 的检查只能 return 错误,因为您的实例名为 singleton_instance。如何以正确的方式做到这一点(也覆盖属性访问):https://python-3-patterns-idioms-test.readthedocs.io/en/latest/Singleton.html

您不需要使用 __new__

class WebDriver:

    class __WebDriver:
        def __init__(self):
            self.driver = webdriver.Chrome(r'C:\webdriver\chromedriver.exe')

    driver = None

    def __init__(self):
        if not self.driver:
            WebDriver.driver = WebDriver.__WebDriver().driver


@given ("website '{url}'")
def website_opener(context,url):
    driver = WebDriver().driver
    driver.get('https://google.com')