PEP 318: Can't we all just get along?
Colin J. Williams
cjw at sympatico.ca
Sat Aug 21 14:12:38 CEST 2004
Neil Zanella wrote:
> 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.
Surely, the price of this is the added complexity in addressing the
Suppose we have a module shape and within it a class Shape. Now suppose
we wish to create some instances of Shape which have no special nethods,
but which each has its own constructor.
One could use a function with shape or a static method within Shape.
We would address the function, from another module as shape.special and
address the static method as shape.Shape.special.
What have we gained from this added complexity? Perhaps we have reduced
the pollution of the space namespace. Is that sufficient justifiction?
> 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
> Now if anyone wishes to add to the list, you're more than welcome.
More information about the Python-list