Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: __cmp__ and __str__?

Tags:

python

methods

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

like image 314
alicew Avatar asked Dec 17 '22 01:12

alicew


2 Answers

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.

like image 172
Drake Guan Avatar answered Dec 18 '22 13:12

Drake Guan


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)
like image 33
wim Avatar answered Dec 18 '22 14:12

wim