用于访问类变量的Python装饰器

标签 python

我有一个装饰器来控制时间限制,如果函数执行超出限制,则会引发错误。

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/

相关文章:

python - lxml etree 解析失败(IOError)

python - 如何使用 Python 和 Selenium WebDriver 获取 localStorage

python - 迭代 .json 文件并更改属性值

python - 将 datetime64[ns, UTC] Pandas 列转换为日期时间

python - 为什么不能 pickle 作为对象属性的列表?

python - 从两个列表中获取元素的所有组合?

python - 用于选择数据的 Pandas 源

python - 为什么 Python 对象的多个实例表现得好像它们是一样的?

python - IronPython 网络框架

python - 当全局变量改变它的值时如何调用函数?