更改d中的实例属性

2024-04-26 05:20:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在寻找这个问题,但我没有找到一个答案,我到底在寻找什么。你知道吗

基本上,我想在try/except子句中包装一个类构造函数,这样它就可以忽略构造函数中特定类型的错误(但无论如何都要记录并打印它们)。我发现最好的方法是用decorator包装我的方法,因为还有其他类我也想这样做,但我不想重复相同的try/except子句。你知道吗

但是,对象必须记住构造函数中是否发生了异常(将其保存在该对象的布尔属性中),以便以后在该对象调用特定方法时使用该信息。所以,我试着在这个片段中这样做:

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名称(这很有意义,因为我试图在类范围之外访问它)。你知道吗

然后,我尝试将decorator作为类成员,然后我尝试将它作为类成员放入Foo的父类中,但是这些替代方法都不起作用。你知道吗

经过一番研究,我意识到修饰符是在定义时解决的,而不是在执行时解决的,因此self不可能以这种方式使用,所以我不知道如何解决这个问题。你知道吗

如果有人知道如何解决这个问题(或者可能是一个更好的解决方案,而不是装饰),这将是非常感谢。你知道吗


Tags: 对象方法selffoodef错误decoratorpass
1条回答
网友
1楼 · 发布于 2024-04-26 05:20:35

包装函数没有名为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

相关问题 更多 >