This is explained in "Special Method Lookup": https://docs.python.org/3/reference/datamodel.html#special-method-lookup
Short version: For both correctness and performance, special methods (those that begin and end with double underscores) are typically looked up on the class, not the instance. If you want to override on a per-instance level, have a non-special method that __str__ invokes, that can be overridden on a per-instance basis. On Sun, Feb 23, 2020 at 2:30 AM Jérôme Carretero <cj-pyt...@zougloub.eu> wrote: > Hello, > > > I just noticed that calling `str(x)` is actually doing (in CPython > `PyObject_Str`) `type(x).__str__(x)` rather than `x.__str__()`. > > Context: I wanted to override __str__ for certain objects in order to > “see them better”. > > I'm wondering why not do `x.__str__()` > > > Best regards, > > -- > Jérôme > _______________________________________________ > Python-ideas mailing list -- python-ideas@python.org > To unsubscribe send an email to python-ideas-le...@python.org > https://mail.python.org/mailman3/lists/python-ideas.python.org/ > Message archived at > https://mail.python.org/archives/list/python-ideas@python.org/message/2VSTPAVKCN6SNOPJG6MOSIP7SDK4W66W/ > Code of Conduct: http://python.org/psf/codeofconduct/ >
_______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-le...@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/KX7KLQXXN4K2VN2GPMBNHPAUBVAVCEV7/ Code of Conduct: http://python.org/psf/codeofconduct/