Wandering Thoughts archives


A real use for staticmethod

In Python, all method functions normally get called with the object as their first argument. New-style classes can specify that some methods should instead be 'static' methods: they don't receive the object as one of their arguments.

On the face of it this is a bit peculiar. Given that Python has ordinary (module-level) functions, why would you ever want to design a staticmethod instead (apart from misplaced object-oriented purity)?

What I use static methods for is as a way of having subclasses specify what piece of data from a data source a 'generic over a class of classes' method function will work on. The pattern looks like:

class Abstract(object):
   def frobnicate(self, datasource):
       work_on = self._pullfrom(datasource)
       # frobnicate work_on
   def fiddle(self, datasource):
       work_on = self._pullfrom(datasource)
       # fiddle with work_on
   # and so on

class RealA(Abstract):
   def _pullfrom(datasource):
       return datasource.thing_a()
class RealB(Abstract):
   def _pullfrom(datasource):
       return datasource.thing_b()

There are alternative patterns for this same effect, but none of them are as simple once the situation itself becomes more complex, such as needing more than one piece of information from the datasource.

python/StaticMethodUse written at 02:40:34; Add Comment

By day for June 2005: 11 12 14 16 17 18 20 21 22 23 24 26 27 28 29; after June.

Page tools: See As Normal.
Login: Password:
Atom Syndication: Recent Pages, Recent Comments.

This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.