language design question
Steven Bethard
steven.bethard at gmail.com
Mon Jul 10 12:29:28 EDT 2006
Bryan wrote:
> Steven Bethard wrote:
>
>> 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.)
>
> could you get the same result by putting these methods in base class
> object that everything subclasses? then you wouldn't have to
> reimplement these methods on your class either, right?
Well, you don't want to put them on object, because not everything is a
container (e.g. you don't want the sorted() method on ints). So you
have to put them on some subclass of object and then require everyone
who every creates a container class to inherit from that object. Python
generally frowns upon required inheritance from a particular type, but
at the same time, it does provide things like UserDict.DictMixin for
something very much along these lines. But I don't think too many folks
want to *require* that every dict-like object inherit from DictMixin.
STeVe
More information about the Python-list
mailing list