how define custom error messages specific invalid attribute calls in python?
i wrote class thats attribute assignment dependent on input on instance creation , return more descriptive error message if unassigned attribute called:
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
on execution error-message
attributeerror: test instance has no attribute 'b'
instead of i'd like
attributeerror: test instance of type 'foo' , therefore has no b-attribute
override getattr in class.
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 of type '{}' , therefore has no {}-attribute.".format(self.type, attr))
getattr called when python can't find attribute normally. essentially, it's "except" clause when class raises attributeerror.
Comments
Post a Comment