0

from an oop viewpoint, why not use str.length() to get the length of a string? just like java. Instead we use len(str). What is the underlying rule to follow here? Thanks.

overcode
  • 13
  • 2
  • Probably an idiosyncrasy or debt there. `len(x)` is syntactic sugar for `x.__len__()` and any custom class can have its custom __len__ method. – Learning is a mess Dec 08 '21 at 14:46
  • Python `len` function ends up calling the `__len__` magic method. So in a sense `len` exists for convenience as it formats the error message if the `__len__` method does not exist. – Olivier Melançon Dec 08 '21 at 14:46
  • See also [this blogpost about python's "principle of least astonishment"](https://lucumr.pocoo.org/2011/7/9/python-and-pola/), which takes len() as its main example. – Stef Dec 08 '21 at 14:54

0 Answers0