__repr__
, callsed by built-inrepr()
, return string representation of a set
__str__
, called by built-instr()
Phython Set
- unordered
- makes the elements uniqure
>>> list = [1,1,2,2,3,3]
>>> set(list)
set([1, 2, 3])
__repr__
goal is to be unambiguous, must
__str__
goal is to be readable, optional
Usually: __str__ = __repr__
>>> class foo(object):
... def __repr__(self):
... return 'foo'
...
>>> print str(foo())
foo
>>> print repr(foo())
foo
>>> class foo(object):
... def __str__(object): return 'foo'
...
>>> print str(foo())
foo
>>> print repr(foo())
<__main__.foo object at 0xb770f64c>
As you see, if you override __repr__
, that’s ALSO used for __str__
, but not vice versa. This means, in simple terms: almost every object you implement should have a functional __repr__
thats usable for understanding the object. Implementing __str__
is optional.