Inherting from object. Or not.

Nick Craig-Wood nick at craig-wood.com
Thu Jan 27 16:30:01 CET 2005


Nick Coghlan <ncoghlan at iinet.net.au> wrote:
>  Exactly. My advice is to use new-style classes unless you have a
>  reason not to (if you're inheriting from a builtin type, then there
>  is no need to inherit from object as well - the builtin types
>  already have the correct basic type).

Except for Exception!

Exception and anything that inherits from it is an old style class.

I discovered the other day that you can't throw a new style class as
an exception at all, eg

>>> class MyException(object): pass
... 
>>> raise MyException
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: exceptions must be classes, instances, or strings (deprecated), not type
>>> 

(not a terribly helpful message - took me a while to work it out!)

wheras old style works fine...

>>> class MyOldException: pass
... 
>>> raise MyOldException
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
__main__.MyOldException: <__main__.MyOldException instance at 0xb7df4cac>
>>> 

After that I recalled a thread on python-dev about it

  http://mail.python.org/pipermail/python-dev/2004-August/046812.html

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list