@@ -215,24 +215,25 @@ objects using the ``for`` statement. For example, :term:`file objects
215
215
Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))?
216
216
----------------------------------------------------------------------------------------------------------------
217
217
218
- The major reason is history. Functions were used for those operations that were
219
- generic for a group of types and which were intended to work even for objects
220
- that didn't have methods at all (e.g. tuples). It is also convenient to have a
221
- function that can readily be applied to an amorphous collection of objects when
222
- you use the functional features of Python (``map() ``, ``zip() `` et al).
223
-
224
- In fact, implementing ``len() ``, ``max() ``, ``min() `` as a built-in function is
225
- actually less code than implementing them as methods for each type. One can
226
- quibble about individual cases but it's a part of Python, and it's too late to
227
- make such fundamental changes now. The functions have to remain to avoid massive
228
- code breakage.
229
-
230
- .. XXX talk about protocols?
231
-
232
- .. note ::
233
-
234
- For string operations, Python has moved from external functions (the
235
- ``string `` module) to methods. However, ``len() `` is still a function.
218
+ As Guido said:
219
+
220
+ (a) For some operations, prefix notation just reads better than
221
+ postfix -- prefix (and infix!) operations have a long tradition in
222
+ mathematics which likes notations where the visuals help the
223
+ mathematician thinking about a problem. Compare the easy with which we
224
+ rewrite a formula like x*(a+b) into x*a + x*b to the clumsiness of
225
+ doing the same thing using a raw OO notation.
226
+
227
+ (b) When I read code that says len(x) I *know * that it is asking for
228
+ the length of something. This tells me two things: the result is an
229
+ integer, and the argument is some kind of container. To the contrary,
230
+ when I read x.len(), I have to already know that x is some kind of
231
+ container implementing an interface or inheriting from a class that
232
+ has a standard len(). Witness the confusion we occasionally have when
233
+ a class that is not implementing a mapping has a get() or keys()
234
+ method, or something that isn't a file has a write() method.
235
+
236
+ -- https://mail.python.org/pipermail/python-3000/2006-November/004643.html
236
237
237
238
238
239
Why is join() a string method instead of a list or tuple method?
0 commit comments