2016-09-14 6 views
1

私のpythonから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() 

は、我々はそれのコンストラクタにdriverを提供してLoginPageを作成することですが、私たちはLoginPageクラスの__init__メソッドを定義していません。

親クラスPageObjectのコンストラクタがdriverパラメータで呼び出されているということですか?私は、Pythonは暗黙のうちに親のコンストラクタを呼び出さないと思った?

+2

、親の実装は、通常、使用されています。 – 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__ PythonはPageObjectクラスを検索し、そこにその定義を見つけ定義していないので。私たちは、「Pythonが暗黙のうちに親クラスのコンストラクタを呼び出すことはありませんが、」あなたは__init__メソッドを定義する場合、インタプリタはちょうどそのメソッドを呼び出すとないコールすべての親クラス__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

関連する問題