2016-09-14 147 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