ElenaT
ElenaT

Reputation: 2630

Python - User-defined classes have __cmp__() and __hash__() methods by default? Or?

In the python docs (yeah, I have this thing with the docs) it says that:

User-defined classes have __cmp__() and __hash__() methods by default; with them, all objects compare unequal (except with themselves) and x.__hash__() returns id(x).

But the following code shows another thing:

>>> class Test(object): pass
...
>>> t = Test()
>>>
>>> t.__hash__
<method-wrapper '__hash__' of Test object at 0x01F2B5D0>
>>>
>>> t.__cmp__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Test' object has no attribute '__cmp__'
>>>

So where is __cmp__ or what am I missing?

Upvotes: 13

Views: 1177

Answers (1)

mipadi
mipadi

Reputation: 410722

The documentation is a bit misleading. To get the full story, you have to read up on __cmp__, namely this part:

If no __cmp__(), __eq__() or __ne__() operation is defined, class instances are compared by object identity (“address”).

So, basically, you don't get a __cmp__ method by default, but instances of user-defined classes can be compared to other objects; if the instance has no __cmp__ method, the object identity (determined by id(obj), which is usually the memory address of the object) will be used instead.

Upvotes: 9

Related Questions