[Tutor] Subclassing object

Alan Gauld alan.gauld at btinternet.com
Sun Jan 17 17:25:09 CET 2010


"Timo Vanwynsberghe" <timovwb at gmail.com> wrote

>I read that it is advised to subclass object.
>
> Is it really necessary? I mean, everything works, why should I add it to 
> my
> code?

In older versions of Python it made a difference whether you used object
or not. Using object gave you a "new style" class which has several extra
features, without you got an "old style class" without the features.

In Python v3 you only get new style classes and I think you can omit
the object without detriment.

For comparison here are Python v2.5 definitions

>>> class New(object): pass
...
>>> dir(New)
['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', 
'__hash_
_', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', 
'__repr_
_', '__setattr__', '__str__', '__weakref__']
>>> class Old: pass
...
>>> dir(Old)
['__doc__', '__module__']

As you can see there is quite a lot of extra "stuff" in the New class.


In Python 3:

>>> class New(object): pass

>>> dir(New)
['__class__', '__delattr__', '__dict__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__gt__', '__hash__',
'__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__', '__weakref__']
>>> class Old: pass

>>> dir(Old)
['__class__', '__delattr__', '__dict__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__gt__', '__hash__',
'__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__', '__weakref__']


There is even more "stuff" but it is the same with/without the explicit 
'object'.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 




More information about the Tutor mailing list