2016-09-14 148 views
1

我下面舉個例子,從蟒蛇page_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() 

讓我困擾的是,我們創建了一個LoginPage與提供driver它的構造,但我們還沒有在LoginPage類中定義的方法__init__

這是否意味着使用driver參數調用父類PageObject的構造函數?我認爲python不會隱式調用父類的構造函數?

+2

如果不定義'__init__'方法,父類的實現時,正常。 – keksnicoh

+1

如果沒有子構造函數,父構造函數會自動運行。 –

回答

1

__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 

同樣是__init__:因爲LoginPage沒有定義__init__蟒蛇中查找PageObject類,發現它的定義存在。

什麼,當我們說「蟒蛇不會隱式調用父類的構造函數」指的是,如果你定義一個__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> 
+0

感謝您的好解釋:) – CuriousGuy