【问题标题】:Define custom error messages on invalid attribute call在无效属性调用上定义自定义错误消息
【发布时间】:2016-11-25 09:00:24
【问题描述】:

如何在 python 中为特定的无效属性调用定义自定义错误消息?

我写了一个类,它的属性分配取决于实例创建时的输入,如果调用未分配的属性,我希望返回更具描述性的错误消息:

class test:
    def __init__(self, input):
        if input == 'foo': 
            self.type = 'foo'
            self.a = 'foo'
        if input == 'bar': 
            self.type = 'bar'
            self.b = 'bar'

class_a = test('foo')

print class_a.a
print class_a.b

执行时我收到此错误消息

AttributeError: test instance has no attribute 'b'

我想得到类似的东西

AttributeError: test instance is of type 'foo' and therefore has no b-attribute

【问题讨论】:

  • inputtype 是 Python 保留字。最好避免使用它们

标签: python class error-handling attributes


【解决方案1】:

在你的类中覆盖 getattr

class test(object):
    def __init__(self, input):
        if input == 'foo': 
            self.type = 'foo'
            self.a = 'foo'
        if input == 'bar': 
            self.type = 'bar'
            self.b = 'bar'

    def __getattr__(self, attr):
        raise AttributeError("'test' object is of type '{}' and therefore has no {}-attribute.".format(self.type, attr))

getattr 在python无法正常找到属性时调用。本质上,当你的类引发 AttributeError 时,它就像一个“except”子句。

【讨论】:

    猜你喜欢
    • 2016-09-03
    • 1970-01-01
    • 2016-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多