If I define a class with its own __str__()
function, is str(a)
equivalent to a.__str__()
, where a
is an instance of my cl
Yes, it does. Take a look at the following example:
>>> class A:
... def __init__(self, a):
... self.a = a
... def __str__(self):
... print "Inside __str__"
... return self.a
...
>>>
>>> a = A('obj1')
>>> a
<__main__.A instance at 0x0000000002605548>
>>>
>>> a.__str__()
Inside __str__
'obj1'
>>>
>>> str(a)
Inside __str__
'obj1'
And, from __str__() documentation, we have:
object.__str__(self)
Called by
str(object)
and the built-in functionsformat()
andprint()
to compute the “informal” or nicely printable string representation of an object. The return value must be a string object.