我有一个装饰器来控制时间限制,如果函数执行超出限制,则会引发错误。
def timeout(seconds=10):
def decorator(func):
# a timeout decorator
return decorator
我想构建一个类,使用构造函数将时间限制传递到类中。
def myClass:
def __init__(self,time_limit):
self.time_limit = time_limit
@timeout(self.time_limit)
def do_something(self):
#do something
但这不起作用。
File "XX.py", line YY, in myClass
@timeout(self.tlimit)
NameError: name 'self' is not defined
实现这个的正确方法是什么?
最佳答案
self.time_limit
仅当调用类实例中的方法时才可用。
另一方面,装饰器语句(为方法添加前缀)在解析类主体时运行。
但是,装饰器的内部部分,如果始终应用于方法,将得到 self
作为它的第一个参数 - 在那里你可以简单地使用任何实例属性:
def timeout(**decorator_parms):
def decorator(func):
def wrapper(self, *args, **kwargs):
time_limit = self.time_limit
now = time.time()
result = func(self, *args, **kwargs)
# code to check timeout
..
return result
return wrapper
return decorator
如果您的装饰器预计会在其他时间限制下工作 self.limit
你总是可以传递一个字符串或其他常量对象,并使用简单的 if
在最里面的装饰器中检查它。陈述。如果超时是某个字符串或对象,则使用实例属性,否则使用传入的值;
关于用于访问类变量的Python装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53088843/