我编写了非常简单的代码,但我想知道这是解决问题的正确方法:
from selenium import webdriver
class MyClass(webdriver.PhantomJS):
def __init__(self, *args, **kwargs):
phantomjs_path = 'node_modules/.bin/phantomjs'
self.driver = webdriver.PhantomJS(phantomjs_path)
super().__init__(phantomjs_path, *args, **kwargs)
我创建了一个类,它继承自selenium.webdriver.PhantomJS
- 当然我执行super()
。另外我创建对象self.driver
。
我可以/应该将最后两行合并为一行吗?
最佳答案
您根本不会使用倒数第二行。您正在您的子类中创建另一个实例。 self.driver
与现在的 self
基本相同,只是没有额外的方法。
完全省略它:
class MyClass(webdriver.PhantomJS):
def __init__(self, *args, **kwargs):
phantomjs_path = 'node_modules/.bin/phantomjs'
super().__init__(phantomjs_path, *args, **kwargs)
在您的方法中,self
已经是实例。
关于Python - 继承、 super 和初始化对象的正确方法(selenium、phantomjs),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29448284/