我有一个装饰器来控制时间限制,如果函数执行超过限制,会抛出一个错误。
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.do_something = timeout(time_limit)(self.do_something)
的操作。这将向每个类实例添加一个函数对象。但是,self
不在类主体的作用域内。 - juanpa.arrivillagaself
只是一个函数的第一个参数。它像其他任何参数一样工作,即在调用函数时创建一个局部变量。 - juanpa.arrivillaga