最近在读 Selenium2Library 的源码,读到一段代码理解不了,求大神指点。
class _ElementKeywords(KeywordGroup):
def __init__(self):
self._element_finder = ElementFinder()
# Public, get element(s)
def _element_find(self, locator, first_only, required, tag=None):
browser = self._current_browser()
if isstr(locator):
elements = self._element_finder.find(browser, locator, tag)
if required and len(elements) == 0:
raise ValueError("Element locator '" + locator + "' did not match any elements.")
if first_only:
if len(elements) == 0: return None
return elements[0]
elif isinstance(locator, WebElement):
elements = locator
# do some other stuff here like deal with list of webelements
# ... or raise locator/element specific error if required
return elements
_element_find
是 Selenium2Library 定义的查找 web element 的方法,第一句是获取当前的 webdriver。但是_current_browser()
不是_ElementKeywords
这个类定义的,而是在_BrowserManagementKeywords
这个类定义的。那么为什么在_ElementKeywords
里面可以用self._current_browser()
调用_BrowserManagementKeywords
定义的方法?
class _BrowserManagementKeywords(KeywordGroup):
def __init__(self):
self._cache = BrowserCache()
self._window_manager = WindowManager()
self._speed_in_secs = float(0)
self._timeout_in_secs = float(5)
self._implicit_wait_in_secs = float(0)
# Public, open and close
def _current_browser(self):
if not self._cache.current:
raise RuntimeError('No browser is open')
return self._cache.current
_ElementKeywords
和_BrowserManagementKeywords
有共同的父类KeywordGroup
。是否是因为它们的父类是由KeywordGroupMetaClass
这个元类定义的?
class KeywordGroupMetaClass(type):
def __new__(cls, clsname, bases, dict):
if decorator:
for name, method in dict.items():
if not name.startswith('_') and inspect.isroutine(method):
dict[name] = decorator(_run_on_failure_decorator, method)
return type.__new__(cls, clsname, bases, dict)
class KeywordGroup(object):
__metaclass__ = KeywordGroupMetaClass
以上,求大神指点