【发布时间】: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
【问题讨论】:
-
input和type是 Python 保留字。最好避免使用它们
标签: python class error-handling attributes