Friday, April 17, 2009

Python: Static Methods versus Class Methods

The best discussion I've seen regarding the differences between static methods and class methods in Python is an old post at Miya's blog.    I like the way Miya approaches it.  Rather than going into the technical discussion found in the Python docs, he asks why would one use static methods, if it seems that class methods can do everything static methods can but not vice versa.

The key to understanding the difference between the two is in the comments.  A commentor points out
"classmethod give[s] you access to the class's attributes. static method does not so..."

Modifying the commentors example slightly:
>>> class MyClass(object):

        myattribute = 'spam'

        @classmethod
        def eggs(cls):
            return cls.myattribute

        @staticmethod
        def static_eggs():
            self.myattribute   # Will this work??
       
>>> MyClass.eggs()            
# O.K. for class method
'spam'
>>> MyClass.static_eggs()    
# ...not so much for static method
Traceback (most recent call last):
  File "<pyshell#33>", line 1, in <module>
    MyClass.static_eggs()
  File "<pyshell#31>", line 8, in static_eggs
    self.myattribute
NameError: global name 'self' is not defined

To recap:
  • Both static and class methods can be called from the class without an instance:
>>>MyClass.static_method_that_says_hi()
"HI"
>>>MyClass.class_method_that_says_hi()
"HI"
>>>x = MyClass()
>>>x.static_method_that_says_hi()
"HI"
  • Both can be inherited by sub-classes and maintain their identity (i.e., both are actually static).
  • Class methods give you access to a class attributes and static methods do not.

So, why use one instead of the other?  Why not just use class methods since they're more powerful?

For me the principle is to use the simplest structure that handle's problem.   Class methods can do more, and therefore using them should signal that you're class does fairly complicated stuff.  Having a bias to using static methods means that you've thought about parsimony in your design. 

I'll come up some examples of each and be back.



No comments:

Post a Comment