覆盖自定义类异常

时间:2019-09-24 13:18:41

标签: python

所以我有这个东西,我不知道我是否可以在python上做。我想处理对未定义变量的访问。示例:

class example():
     def __init__():
          self.variableA = 'jaa'
     def set_b(self):
          self.variableB = 'nope'

在这里,如果我实例化示例的对象X并尝试在不调用x.set_b()的情况下访问variableB,则会收到Class has no attribute错误。有什么办法可以深入研究此异常?我想返回一条自定义消息并出错。

1 个答案:

答案 0 :(得分:1)

我可以建议执行以下操作:

class Example():
    def __init__(self):
        self.variableA = 'jaa'
        self._variableB = None

    @property
    def variableB(self):
        if self._variableB is None:            
            return 'Sorry, you need to set this using `Set_b` first'
            # better would probably be
            # raise AttributeError("'Sorry, you need to set this using `Set_b`")

        return self._variableB

    @variableB.setter
    def variableB(self, value):
        raise AttributeError("'Sorry, you need to set this using `Set_b`")

    def set_b(self):
        self._variableB = 'nope'

example = Example()
print(example.variableB)  # Sorry, you need to set this using `Set_b` first
try:
    example.variableB = 'mymy'
except Exception as error:
    print(repr(error))  # AttributeError('Sorry, you need to set this using `Set_b`)

example.set_b()
print(example.variableB)  # 'nope