0

In python documentation here and here:

str(object) returns object.__str__(), which is the “informal” or nicely printable string representation of object.

But I think it is wrong:

Python 3.5.2 (default, Nov 23 2017, 16:37:01)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help.

In [1]: class A:
   ...:     def __str__(self):
   ...:         return 'a'
   ...:

In [2]: def f():
   ...:     return 'b'
   ...:

In [3]: a=A()

In [4]: a.__str__=f

In [5]: a.__str__()
Out[5]: 'b'

In [6]: str(a)
Out[6]: 'a'

In [7]: repr(a)
Out[7]: '<__main__.A object at 0x7ffd387c71d0>'

str(a) is not returning a.__str__() according to the documentation.

Is this behaviour documented anywhere? Or is it a bug?

zzh1996
  • 480
  • 4
  • 13
  • Your `f()` does not accept `self`, so `[5]` should fail. – Klaus D. Dec 17 '17 at 14:34
  • Function f doesn't need to accept self, since it is assigned to a, not to A. OP is right in signaling deviant behaviour here. – Jacques de Hooge Dec 17 '17 at 14:40
  • Special methods are special, they are looked up on the class if implicitly called, not on the instance. The relevant documentation can be found here: ["Special method lookup"](https://docs.python.org/reference/datamodel.html#special-method-lookup) – MSeifert Dec 17 '17 at 15:13

0 Answers0