PEP 318: Can't we all just get along?

Neil Zanella nzanella at cs.mun.ca
Fri Aug 20 13:48:47 EDT 2004


Paul Morrow <pm_mon at yahoo.com> wrote in message news:<mailman.2020.1092995114.5135.python-list at python.org>...
> Roy Smith wrote:
> > 
> > I never quite understood the point of static methods inside classes.  
> > When would you ever need to do that, as opposed to just a function in a 
> > module?  In Java's "everything is part of a class" philosophy, it makes 
> > sense, but in Python?
> 
> It gives us another means of managing namespaces.  Rather than having to 
> create a top-level function in the current (or some other) module, we 
> can group it with other related functions as a method in a class.

This is one reason for using staticmethod. However, as I pointed out, there
is another even better reason. It allows you to use the polymorphism feature
(as in C++ virtual functions) on class objects without having to create class
instances (as would be necessary in C++). For instance, you can have a
superclass with 20 staticmethods with default behavior, and 40 subclasses
each ovrriding 5 of these staticmethods on average and using the default
for the rest.

To summarize, here are the two reasons to use staticmethod:

1. You want to group a bunch of functions together. However, as it happens
   such functions are not useful outside of a given class, so you use
   staticmethod to place them where they belong. Perhaps you do not
   have enough such functions to warrant their placement inside a
   module of its own.

2. You need to use inheritance and polymorphism but you don't need instances,
   or perhaps you simply need instance independent polymorphism at the class
   level.

Now if anyone wishes to add to the list, you're more than welcome.

Regards,

Neil



More information about the Python-list mailing list