4

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

Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
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
  • 14,514
  • 15
  • 67
  • 94
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
  • 338,267
  • 99
  • 616
  • 750