Although the reason is mostly historical, there are some features in Python len that make using a function instead of a suitable method.
Some operations in Python are implemented as methods, for example list.index and dict.append , while others are implemented as calling and magic methods, for example str and iter and reversed . These two groups differ from each other so much that a different approach is justified:
- They are common.
str , int and friends are types. It makes sense to call the constructor.- The implementation is different from calling a function. For example,
iter can call __getitem__ if __iter__ not available, and supports additional arguments that do not match the method call. For the same reason, it.next() been changed to next(it) in recent versions of Python - it makes sense. - Some of them are close relatives of the operators. There is syntax for calling
__iter__ and __next__ - it called the for loop. For consistency, the function is better. And that makes it better for certain optimizations. - Some of the functions are just too similar to the others in some way -
repr acts like str . str(x) vs x.repr() will be confused. - Some of them rarely use the actual implementation method, for example,
isinstance . - Some of them are valid operators,
getattr(x, 'a') is another way to make xa and getattr shares many of the above qualities.
I personally call the first group method, and the second - operator. This is not a very good difference, but I hope this helps in some way.
Having said that, len doesn't exactly match in the second group. This is closer to the operations in the first, with the only difference being that it is more common than almost any of them. But the only thing he does is call __len__ , and he is very close to L.index . However, there are some differences. For example, __len__ can be called to implement other functions, such as bool , if this method was called len , you can break bool(x) with the custom len method, which does a completely different thing.
In short, you have a set of very general functions that can be implemented by classes, which can be accessed through an operator, through a special function (which usually does more than an implementation, like an operator), when building an object, and they all have some common features . Everything else is a method. And len is a bit of an exception to this rule.
Rosh Oxymoron Mar 05 2018-11-11T00: 00Z
source share