在 Python 中扩展现有的类实例

我有一个element由另一个类方法返回的对象,我不一定有权更改。


>>> from selenium.webdriver import Chrome

>>> browser = Chrome()

>>> browser.get('https://www.google.com')

>>> element = driver.find_element_by_tag_name('input')

>>> type(element)

<class 'selenium.webdriver.remote.webelement.WebElement'>   

我有一个单独的类来扩展元素的功能。


>>> class Input:

>>>     def __init__(self, element):

>>>         assert element.tag_name == 'input', 'Element must be of type "input"'

>>>         self.element = element

>>>         self.browser = element.parent

>>>     def is_enabled(self):

>>>         return self.element.is_enabled()

>>>     @property

>>>     def value(self):

>>>         return self.element.get_attribute('value')

目前我使用它的方式是传递element给类:


>>> input = Input(element)

>>> input.is_enabled() # Same as input.element.is_enabled()

True

我希望能够更轻松地访问原始对象的属性,而不必在调用中指定它。例如:


而不是这个:


>>> input.element.tag_name

'input'

做这个:


>>> input.tag_name

'input'

我将如何实现这样的事情?


森林海
浏览 132回答 1
1回答

白板的微信

您可以Input通过实现该__getattr__()方法将您的类转换为代理,如Container下面的类:class Example:&nbsp; &nbsp; def __init__(self):&nbsp; &nbsp; &nbsp; &nbsp; self.tag_name = 'name'&nbsp; &nbsp; def foo(self):&nbsp; &nbsp; &nbsp; &nbsp; return 'foo'&nbsp; &nbsp; def bar(self, param):&nbsp; &nbsp; &nbsp; &nbsp; return paramclass Container:&nbsp; &nbsp; def __init__(self, contained):&nbsp; &nbsp; &nbsp; &nbsp; self.contained = contained&nbsp; &nbsp; def zoo(self):&nbsp; &nbsp; &nbsp; &nbsp; return 0&nbsp; &nbsp; def __getattr__(self, item):&nbsp; &nbsp; &nbsp; &nbsp; if hasattr(self.contained, item):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return getattr(self.contained,item)&nbsp; &nbsp; &nbsp; &nbsp; #raise itemc = Container(Example())print(c.foo())print(c.bar('BAR'))print(c.tag_name)输出:fooBARname该类Container现在将任何未知属性访问转发给其contained成员,当然,该成员可能具有也可能没有所需的属性。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python