language design question
Steven Bethard
steven.bethard at gmail.com
Mon Jul 10 00:29:10 EDT 2006
guthrie wrote:
> Steven Bethard wrote:
>> Why would ``x.len()`` be any more convenient than ``len(x)``? Your
>> preference here seems pretty arbitrary.
> -- Perhaps;
> but having all standard operations as a method seems more regular (to
> me), and allows a simple chained operation format of a series of method
> calls, instead of alternating prefix function calls, and post-fix method
> invocations; e.g.
> x.lower().strip().toList().sort().join()
> seems cleaner and simpler than the usage below, where the pre/post
> alternation is visually more complex.
> I think the mix of OO like methods, and global functions, is not ideal.
The advantage of a functional form over a method shows up when you write
a function that works on a variety of different types. Below are
implementations of "list()", "sorted()" and "join()" that work on any
iterable and only need to be defined once::
def list(iterable):
result = []
for item in iterable:
result.append(item)
return result
def sorted(iterable):
result = list(iterable)
result.sort()
return result
def join(iterable):
# this is more efficient in C, where the string's buffer can be
# pre-allocated before iterating through the loop.
result = ''
for item in iterable:
result += item
return result
Now, by providing these as functions, I only have to write them once,
and they work on *any* iterable, including some container object that
you invent tomorrow.
If everything were methods, when you invented your container object
tomorrow, you'd have to reimplement these methods on your class. (Or
we'd have to introduce a Container class to provide them, and everyone
would have to inherit from that if they wanted to define a container.)
>>> - Why doesn't sort() return a value?
>>>
>>> This would allow things like:
>>> key = '',join( list(word.lower().strip()).sort() )
>>
>> Use sorted():
>>
>> key = ','.join(sorted(word.lower().strip()))
> -- Thanks!
> (Is the comma in ',' just a typo?)
No, the comma puts a comma between each item. I wasn't sure whether the
comma in your original was a typo for ''. or for ','. Of course if you
don't want the comma between each item, you should just use ''
STeVe
More information about the Python-list
mailing list