language design question

Bryan belred at gmail.com
Mon Jul 10 01:29:56 EDT 2006


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?  i'm not arguing for one method or the other.  just 
curious about the difference.

bryan




More information about the Python-list mailing list