更改实例返回的内容

2021-09-27 05:24:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经为selenium webdriver创建了一个单例包装器。你知道吗

class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

class Driver(metaclass=Singleton):   
        """Ensures theres only 1 Driver open at any time.
        If the driver is closed, tries to quit the previous
        instance, and recreates a new one"""

        def __init__(self):
            self._driver = self.load_selenium_driver()

    @staticmethod
    def load_selenium_driver():
        _chrome_driver_locn = CHROME_DRIVER_LOCATION
        _driver =  webdriver.Chrome(_chrome_driver_locn)
        return _driver

    @property
    def driver(self):
        """Creates a new driver if the previous one is closed,
        and quits the instance of the chrome driver."""
        if self._web_browser_is_open():
            return self._driver
        else:
            try:
                self._driver.quit()
            finally:
                self._driver = self.load_selenium_driver()
                return self._driver

    def _web_browser_is_open(self):
        try:
            self._driver.title
            return True
        except WebDriverException:
            return False

运行a = Driver() 我想访问Driver.driver方法,在a中,这样我就不需要做a.driver.get('google.com'),而是a.get('google.com')。你知道吗

问题是:

如何生成Driver的实例,返回driver对象(在属性Driver.driver中找到),而不是Driver的实例?你知道吗