[英]How to use a decorator of class method
When I design a class, I wrote a class member function as a decorator当我设计一个 class 时,我写了一个 class 成员 function 作为装饰器
def switchWindow(self, win: str):
def actual_decorator(func):
self.browser.switch_to.window(self.windowsHandles[win])
def inner():
func()
return inner
return actual_decorator
the decorator is used to change the eviroment for other member function before they're running, however, when I used the decorator over a member function like this:装饰器用于在其他成员 function 运行之前更改环境,但是,当我在成员 function 上使用装饰器时,如下所示:
@switchWindow(win="crop")
def test_cropFunction(self):
pass
the IDE raised an error like this: IDE 引发如下错误:
@switchWindow(win="crop") TypeError: switchWindow() missing 1 required positional argument: 'self'
I'm confused by the error, but then I rewrote the decorator by add a 'self' before the decorator, but it's also wrong:我对这个错误感到困惑,但后来我通过在装饰器之前添加一个“自我”来重写装饰器,但这也是错误的:
@self.switchWindow(win="crop") NameError: name 'self' is not defined
can anyone help me out?谁能帮我吗?
I move the decorator function out of the class, and make some changes like this:我将装饰器 function 从 class 中移出,并进行如下更改:
def switchWindow(win: str):
def actual_decorator(func):
print(win)
def inner(self):
self.browser.switch_to.window(self.windowsHandles[win])
func(self)
return inner
return actual_decorator
and now it works!现在它可以工作了!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.