更改实例返回python的内容

时间:2018-04-27 09:33:37

标签: python inheritance singleton

我为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的实例?

1 个答案:

答案 0 :(得分:0)

从评论中的讨论来看,我所要求的是不可能的。