Deriving from Exception
Fredrik Lundh
fredrik at pythonware.com
Wed Jul 10 05:51:14 EDT 2002
"pixie888 at hotmail.com" wrote:
> I have some classes which derive from Exception, however in the
> __init__ function I do not call the __init__ function of Exception
> itself, allthough I think I should. The reason I don't do it is
> because I see that in all the tutorials about Python the tutors
> themselves don't do it either.
>
> Can anybody tell me why?
The Exception baseclass provides an __init__ method which
takes all arguments and puts them in an args attribute.
It also provides default __str__ and __getitem__ methods,
so you can print the exception, and use the v[x] notation
to access the members.
In Python, the class would look something like this:
class Exception:
def __init__(self, *args):
self.args = args
def __str__(self):
if not self.args:
return ''
elif len(self.args) == 1:
return str(self.args[0])
else:
return str(self.args)
def __getitem__(self, i):
return self.args[i]
If this behaviour is fine for your exception subclass, there's
no need to override anything.
</F>
More information about the Python-list
mailing list