interactive help on the base object

Steven D'Aprano steve at pearwood.info
Mon Dec 9 00:44:34 EST 2013


On Sun, 08 Dec 2013 18:41:47 -0800, Mark Janssen wrote:

>>> What methods, if any does it provide?  Are they all abstract? etc???
>>
>> Pretty much nothing useful :-)
>>
>> py> dir(object)
>> [...]
>>
>>
> So (prodding the student), Why does everything inherit from Object if it
> provides no functionality?

You cut out the part of my post where I explained that object does in 
fact provide a minimal set of useful functionality. The example I gave 
was __eq__ (equal), but there is also __ne__ (not equal), __hash__ 
(hashing), __str__ and __repr__ (although many classes will wish to 
override them) and a few more. They're useful, even necessary, but hardly 
exciting.

The other reasons for inheriting from object include:

- If all classes are part of a single hierarchy, it must logically end at 
one (or more, if you support multiple inheritance, which Python does) 
bases classes. (Unless there are loops, which are generally prohibited in 
all OOP systems I know of). The simplest way to do this is with a single 
base class.

- Pragmatism: it was the easiest way to unify types and classes way back 
in Python 2.2, prior to which there was no single hierarchy and all 
classes were (in a sense) distinct.

Pedants will of course realise that Python 2 has *two* object 
hierarchies, classic classes which don't share a base class, and types 
(a.k.a. "new style classes") which do. In Python 3, classic classes are 
gone, and there is a single class hierarchy with object the base.


There may be other reasons.



-- 
Steven



More information about the Python-list mailing list