[Tutor] methods versus functions (using lists as an example)

Jeff Shannon jeff at ccvcorp.com
Tue Oct 19 23:02:44 CEST 2004

Max Noel wrote:

> On Oct 19, 2004, at 15:29, Hans Fangohr wrote:
>> I was looking at what you can do with lists in Python. There are
>> basically two sets of commands: (i) methods doing something with a
>> list (such as sort(), reverse(), count(), ...) and (ii) functions that
>> take a list as an argument (such as sum(), max(), min()).
>> I would expect that there is a rationale behind this choice -- would
>> anyone know what this is or where I can find more information?
>     It's a matter of legacy. IIRC, Python was not, in its original 
> design, fully object-oriented. Which is why some functions haven't 
> been implemented as base class methods yet.

Not true.  Python is object-oriented from the ground up, and everything 
in Python (including basic data types, functions, modules, and even 
class definitions themselves) is an object.

The reason that some of these things are done as functions and some as 
methods of list objects, is that some of the operations make sense on a 
much wider range of things than just lists.  If you want to be able to 
conveniently sum a sequence, you can pass that sequence to sum() and 
everything just works.  If sum() were a method instead of a function, 
then *every* type of sequence would have to define a sum() method that 
would be essentially identical.  Even worse, if a programmer defines his 
own sequence type, then he'd have to write a sum() method on that custom 
type before it could be summed.  Not much of a problem if it's known 
ahead of time that sum() is needed, but what if you're writing a 
library?  You don't know how that type is going to be used, which means 
you need to implement methods for every possible type of action that 
could be done on a sequence... what a pain!  Especially since those 
methods will be identical to the methods on built-in lists and tuples...

In other words, using functions instead of methods can make generic 
programming much easier.  Python's design is carefully tuned to 
encourage generic programming, which makes it easier to re-use code, 
which means that you'll end up being more productive.

>  This makes Python slightly less elegant than Ruby, but it's quite 
> easy to get the hang of.

I don't know Ruby, but I can certainly say that I think that Python's 
current form (using functions for generic operations and methods only 
for type-specific operations) is far more elegant than it would be if 
everything were forced into methods, thus requiring many classes to 
sprout swarms of tiny, repetitious methods...

But I *do* agree that Python is quite easy to get the hang of. ;)

Jeff Shannon
Credit International

More information about the Tutor mailing list