Does python `str()` function call `__str__()` function of a class?

前端 未结 3 1822
礼貌的吻别
礼貌的吻别 2020-12-10 04:06

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

3条回答
  •  感情败类
    2020-12-10 05:06

    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.

提交回复
热议问题