Cur*_*Guy 3 python oop selenium selenium-webdriver
我有来自 pythonpage_object
文档的以下示例:
from page_objects import PageObject, PageElement
from selenium import webdriver
class LoginPage(PageObject):
username = PageElement(id_='username')
password = PageElement(name='password')
login = PageElement(css='input[type="submit"]')
driver = webdriver.PhantomJS()
driver.get("http://example.com")
page = LoginPage(driver)
page.username = 'secret'
page.password = 'squirrel'
assert page.username.text == 'secret'
page.login.click()
Run Code Online (Sandbox Code Playgroud)
困扰我的是我们创建了一个LoginPage
并为其driver
构造函数提供了一个,但是我们没有__init__
在LoginPage
类中定义一个方法。
这是否意味着PageObject
使用driver
参数调用父类的构造函数?我认为 python 不会隐式调用父的构造函数?
该__init__
方法只是一个方法,因此 python 执行与其他方法相同类型的查找。如果类B
没有定义方法/属性,x
那么python查找它的基类A
等等,直到它找到属性/方法或失败。
一个简单的例子:
>>> class A:
... def method(self):
... print('A')
...
>>> class B(A): pass
...
>>> class C(B):
... def method(self):
... print('C')
...
>>> a = A()
>>> b = B()
>>> c = C()
>>> a.method()
A
>>> b.method() # doesn't find B.method, and so uses A.method
A
>>> c.method()
C
Run Code Online (Sandbox Code Playgroud)
同样是__init__
: 因为LoginPage
没有定义__init__
python 查找PageObject
类并在那里找到它的定义。
当我们说“python 不会隐式调用父类构造函数”时的意思是,如果您定义一个__init__
方法,解释器将只调用该方法而不调用所有父类__init__
,因此如果您想调用父类构造函数你必须明确地这样做。
请注意这些类之间的区别:
>>> class A:
... def __init__(self):
... print('A')
...
>>> class B(A):
... pass
...
>>> class B2(A):
... def __init__(self):
... print('B')
...
>>> class B3(A):
... def __init__(self):
... print('B3')
... super().__init__()
...
>>> A()
A
<__main__.A object at 0x7f5193267eb8>
>>> B() # B.__init__ does not exists, uses A.__init__
A
<__main__.B object at 0x7f5193267ef0>
>>> B2() # B2.__init__ exists, no call to A.__init__
B
<__main__.B2 object at 0x7f5193267eb8>
>>> B3() # B3.__init__exists, and calls to A.__init__ too
B3
A
<__main__.B3 object at 0x7f5193267ef0>
Run Code Online (Sandbox Code Playgroud)