gpt4 book ai didi

python - 更 retrofit 饰器内的实例属性

转载 作者:行者123 更新时间:2023-12-01 01:40:12 29 4
gpt4 key购买 nike

我已经搜索过这个问题,但没有找到我正在寻找的答案。

基本上,我想将类构造函数包装在 try/except 子句中,以便它忽略构造函数内特定类型的错误(但无论如何都会记录并打印它们)。我发现做到这一点的最好方法是用装饰器包装我的方法,因为我想在其他类中执行相同的操作,但我不想继续重复相同的 try/except 子句。

但是,对象必须记住构造函数中是否发生了异常(将其保存在该对象的 bool 属性中),以便稍后当该对象调用特定方法时可以使用该信息之后。所以,我尝试做类似以下代码片段的事情:

def detectAndIgnoreErrors(fn):
def wrappedFunc(*args, **kwargs):
try:
fn(*args, **kwargs)
self.HasAnExceptionOccurredInInit = False
except KeyError as e:
self.HasAnExceptionOccurredInInit = True
# Log and print exception
except RuntimeError as e:
self.HasAnExceptionOccurredInInit = True
# Log and print exception

return wrappedFunc


class Foo(FooSuperclass):

@detectAndIgnoreErrors
def __init__(self):
# Do stuff that may raise exceptions
pass

def doStuff(self):
if self.HasAnExceptionOccurredInInit:
# Do stuff
pass
else:
# Do other stuff
pass

fooInstance = Foo()
fooInstance.doStuff()

这里的想法是让对象忽略构造函数中的错误,然后当 doStuff() 时方法被调用时,对象会记住是否发生了异常 HasAnExceptionOccurredInInit并相应地调整其行为。然而,解释器说 self名称未定义(这是有道理的,因为我试图在类范围之外访问它)。

然后,我尝试将装饰器作为类成员,然后又尝试将其作为 Foo 父类的类成员,但这些替代方案都不起作用。

经过一番研究,我意识到装饰器是在定义时解析的,而不是在执行时解析的,所以没办法self可以这样使用,所以我不知道如何解决这个问题。

如果有人知道如何解决这个问题(或者可能是一个比装饰器更好的解决方案),我们将非常感激。

最佳答案

包装的函数没有名为 self 的参数;如果您打算假设 fn 是一个方法,则需要特别指定。

def detectAndIgnoreErrors(fn):
def wrappedFunc(self, *args, **kwargs):
try:
fn(self, *args, **kwargs)
self.HasAnExceptionOccurredInInit = False
except KeyError as e:
self.HasAnExceptionOccurredInInit = True
# Log and print exception
except RuntimeError as e:
self.HasAnExceptionOccurredInInit = True
# Log and print exception

return wrappedFunc

关于python - 更 retrofit 饰器内的实例属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51974760/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com