【发布时间】:2016-09-02 15:20:55
【问题描述】:
我想在我的 Python 类中使用它创建一个内部装饰器,用于包装 selenium 框架的进出操作。所以我尝试了这个:
class MyPage(object):
# ...
def framed(self, frame_query: str):
def decorator(function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
frame = self.driver.find_element(By.XPATH, frame_query)
self.driver.switch_to.frame(frame)
out = function(*args, **kwargs)
self.driver.switch_to.default_content()
return out
return wrapper
return decorator
# ...
@framed('//myxpath/iframe')
def framed_function(self):
# ...
然后我收到此错误:
TypeError: framed() missing 1 required positional argument: 'frame_query'
显然它需要 2 个参数,包括 self,但在装饰器上下文中,它对 self 一无所知,因此我必须在“framed_function”中定义内部函数,从而使解决方案不那么优雅:
# My workaround
def framed_function(self):
@framed('//myxpath/iframe')
def actual_framed():
#...
actual_framed()
建议?
【问题讨论】:
标签: python python-3.x oop decorator python-decorators