Trying to come to grips with static methods

Robert Kern rkern at ucsd.edu
Tue Jul 12 11:06:41 CEST 2005


Steven D'Aprano wrote:
> I've been doing a lot of reading about static methods in Python, and I'm
> not exactly sure what they are useful for or why they were introduced.
> 
> Here is a typical description of them, this one from Guido:
> 
> "The new descriptor API makes it possible to add static methods and class
> methods. Static methods are easy to describe: they behave pretty much like
> static methods in C++ or Java."
> http://www.python.org/2.2.3/descrintro.html
> 
> Great. So I have learn an entire new language to understand static
> methods. Perhaps not -- hence this cry for help.
> 
> As near as I can see it, static methods are object methods that act just
> like functions. Er. I always thought that object methods *were* functions,
> except they had some runtime magic that passed the object itself as the
> first argument.

[snip]

> What are some usage cases for using Class.StaticMethod() instead of
> instance.method()? Everything I've read seems to just assume that the
> benefits of static methods are so obvious that they don't need explaining.
> Unfortunately, I haven't come from a background in OO and I'm easily
> confused, hence this post.

staticmethods don't see a whole lot of use in Python. They see use in 
Java because everything has to be stuck in a class, even if they don't 
actually require an instance of the class to work. In Python, you 
usually just define a function. I think staticmethod was implemented 
along with classmethod primarily for completeness than anything else.

OTOH, I do find myself using them occasionally to group such functions 
appropriately. I'll be writing a utility method that doesn't actually 
need an instance or the class to be passed in, so I make it a 
staticmethod. It *could* just as well be a module-level function, but 
sometimes it really belongs tucked in with the class. It could also be a 
regular method, but then I can't call it from the outside without 
actually having an instance which isn't actually needed. It could also 
be a classmethod, but since it doesn't actually need any information 
from the class to do its work, I find that the extra reminder of 
staticmethod helps my brain understand what it's doing.

All told, I'd probably vote -0.5 on a builtin staticmethod if it came up 
today.

-- 
Robert Kern
rkern at ucsd.edu

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter




More information about the Python-list mailing list