|
Original |
Translation |
|
47
|
for line in f: ... # do something with line...
|
|
|
48
|
Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))?
|
|
|
49
|
The major reason is history. Functions were used for those operations that were generic for a group of types and which were intended to work even for objects that didn't have methods at all (e.g. tuples). It is also convenient to have a function that can readily be applied to an amorphous collection of objects when you use the functional features of Python (``map()``, ``apply()`` et al).
|
|
|
50
|
In fact, implementing ``len()``, ``max()``, ``min()`` as a built-in function is actually less code than implementing them as methods for each type. One can quibble about individual cases but it's a part of Python, and it's too late to make such fundamental changes now. The functions have to remain to avoid massive code breakage.
|
|
|
51
|
|
52
|
Why is join() a string method instead of a list or tuple method?
|
|
|
53
|
Strings became much more like other standard types starting in Python 1.6, when methods were added which give the same functionality that has always been available using the functions of the string module. Most of these new methods have been widely accepted, but the one which appears to make some programmers feel uncomfortable is::
|
|
|
54
|
", ".join(['1', '2', '4', '8', '16'])
|
|
|
55
|
|
|
|
56
|
|
|