gpt4 book ai didi

python - 如何从Python中的__new__构造函数调用方法?

转载 作者:行者123 更新时间:2023-12-01 04:09:34 25 4
gpt4 key购买 nike

我试图在 __new__ 方法中调用 get_driver_path,当我尝试运行完整代码时出现此错误:

TypeError: unbound method get_chrome_driver() must be called with
WebBrowserManager instance as first argument (got str instance instead

这是代码:

def __new__(self, driver = 'firefox'):
if not self._instance:
self._instance = super(WebBrowserManager, self).__new__(self)
self._profile.native_events_enabled = True
self.data = {}
self._system = platform.system()
if self._local:
if driver == 'firefox':
self.browser = webdriver.Firefox(self._profile)
elif driver == 'chrome':
self.browser = self.get_chrome_driver(self._system, driver)
elif driver == 'ie':
assert self._system == 'Windows', 'Tests on Internet Explorer are only supported on Windows'
self.browser = webdriver.Ie(self.get_driver_path(driver))
return self._instance

def get_driver_path(self, driver):
driver_name = ''
if driver == 'ie':
driver_name = 'IEDriverServer.exe'
elif driver == 'chrome':
driver_name = 'chromedriver.exe'
driver_path = "selenium_drivers\\" + driver_name
os.environ["webdriver." + driver + ".driver"] = driver_path
return driver_path

最佳答案

由于您将其设为实例方法,因此您需要在 __new__ 方法中创建的实例上调用它(该方法是静态的;例如,未绑定(bind)到实例或类):

self.browser = webdriver.Ie(self._instance.get_driver_path(driver))

您可以将该方法设置为静态方法或类方法,此时您可以通过 __new__ 的第一个参数来使用它(这是类,而不是实例;通常您不会使用名称 self 但改为 cls):

@staticmethod
def get_driver_path(driver):

请注意,staticmethod 不会采用 self 参数,但您的 get_driver_path() 实现无论如何也不会使用该参数。

关于python - 如何从Python中的__new__构造函数调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35140524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com