4

What happens if you don't define your own for methods __cmp__ and __str__?

Jeff Mercado
  • 121,762
  • 30
  • 236
  • 257
alicew
  • 275
  • 1
  • 2
  • 6

2 Answers2

6

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

For more detailed info: refer to object.__cmp__(self, other) in Python. And you can get further references Special (magic) methods in Python.

Community
  • 1
  • 1
Drake Guan
  • 13,644
  • 11
  • 59
  • 92
6

With no __str__ defined, you will get the default one with the memory address e.g. <__main__.A object at 0x165aa90>.

If no __cmp__() operation is defined, class instances are compared by object identity i.e. memory address (docs).

Examples:

>>> class A(object):
...   pass
... 
>>> a = A()
>>> b = A()
>>> str(a)
'<__main__.A object at 0x7fcb1df8acd0>'
>>> hex(id(a))
'0x7fcb1df8acd0'
>>> a < b
False
>>> a > b
True
>>> id(a), id(b)
(140510357925072, 140510357925008)
wim
  • 302,178
  • 90
  • 548
  • 690