interactive help on the base object

Chris Angelico rosuav at gmail.com
Sun Dec 8 21:57:28 EST 2013


On Mon, Dec 9, 2013 at 1:41 PM, Mark Janssen <dreamingforward at gmail.com> 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?
>
> Practicality-beats-purity-yours?

Nothing useful to call directly. An int has some useful methods in Python:

>>> (258).to_bytes(2,"little")
b'\x02\x01'

So does a list:

>>> [1,4,1,5,9].count(1)
2

But there's nothing you'd normally want to call from object itself
(except maybe __repr__). There *are*, however, important pieces of
default functionality. Steven mentioned __eq__, and there's also its
pair __hash__. The default system works because the root type provides
implementations of those two functions:

>>> a = object()
>>> b = object()
>>> a == b
False
>>> d = {a:"A", b:"B"}
>>> d[a]
'A'

And it's important that these sorts of things work, because otherwise
a simple Python class would look like this:

class Foo:
    def __new__(self): pass
    def __init__(self): pass
    def __hash__(self): return id(self)
    def __eq__(self, other): return self is other
    # ...

This repetition is exactly what inheritance is good at solving.
Therefore putting that functionality into a base class makes sense;
and since everything MUST have these functions to be able to be used
plausibly, putting them in the lowest base class of all makes the most
sense.

ChrisA



More information about the Python-list mailing list