23

If I define a class with its own __str__() function, is str(a) equivalent to a.__str__(), where a is an instance of my class?

I checked the python doc, it doesn't say explicitly that this is the case.

3
  • Why not try it out yourself? Commented Dec 15, 2016 at 16:30
  • 2
    Why don't you test it? Make a new class, and override the __str__ method. Commented Dec 15, 2016 at 16:30
  • 1
    See the str doc Commented Dec 15, 2016 at 16:40

3 Answers 3

29

Short answer: Yes!


According to the Python docs (I highlighted the relevant part):

object.__str__(self)

Called by str(object) and the built-in functions format() and print() to compute the “informal” or nicely printable string representation of an object. The return value must be a string object.

This method differs from object.__repr__() in that there is no expectation that __str__() return a valid Python expression: a more convenient or concise representation can be used.

The default implementation defined by the built-in type object calls object.__repr__().

So your_instance.__str__ is generally called when you do str(your_instance).


Longer answer: With "Special Methods" (the methods with two leading underscores and two trailing underscores) there is an exception because these are looked up on the class, not the instance. So str(a) is actually type(a).__str__(a) and not a.__str__(). But in most cases these are the same, because one rarely overrides methods of the class on the instance. Especially not special methods.

See also the relevant documentation on "Special method lookup":

For custom classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an object’s type, not in the object’s instance dictionary.

So like @zzh1996 pointed out in the comments the following code will use the method defined on the class even though the instance has a custom callable __str__ attribute:

>>> class A(object):
...     def __str__(self):
...         return 'a'
>>> instance = A()
>>> instance.__str__ = lambda: 'b'
>>> str(instance)
'a'
>>> instance.__str__()
'b'
Sign up to request clarification or add additional context in comments.

4 Comments

this is wrong! ``` In [21]: class A: ...: def __str__(self): ...: return 'a' ...: ...: In [22]: a=A() In [23]: def f(): ...: return 'b' ...: In [24]: a.__str__=f In [25]: str(a) Out[25]: 'a' ```
@zzh1996 Yes, special methods are looked up on the class, not the instance. However I thought that would distract from the actual question which asked if "str() function call __str__() function of a class?" (which is the case) but str(a) is not always equivalent to a.__str__() but to type(a).__str__(a). But I added further clarification on that point.
Note that if the class (or its parents) doesn't define .__str__ then .__repr__ will be called. The latter always exists because it's inherited from object, unless it's overridden by the class (or a parent).
Yeah that's correct. It is also mentioned in the docs i copied: "The default implementation defined by the built-in type object calls object.__repr__().". Do you that needs to be emphasised?
3

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 functions format() and print() to compute the “informal” or nicely printable string representation of an object. The return value must be a string object.

Comments

1

Yes, but also on print. See docs https://docs.python.org/2/reference/datamodel.html#object.str

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.