[Tutor] classmethod, staticmethod functions (decorator related)

Steven D'Aprano steve at pearwood.info
Sat Sep 11 12:13:11 CEST 2010


On Sat, 11 Sep 2010 12:35:48 am Huy Ton That wrote:
> I am reading the decorator section within Expert Python Programming
> and I am very confused in the first example, of a method that was
> done before decorators. It reads:
>
> class WhatFor(object):
>     def it(cls):
>         print 'work with %s' % cls
>     it = classmethod(it)
>     def uncommon():
>         print 'I could be a global function'
>     uncommon = staticmethod(uncommon)
>
> But I can't seem to understand the above. Under what circumstance
> would staticmethod be useful? I am just deriving that you are not
> passing self.


They usually aren't, in Python, because if you think you want a 
staticmethod, you're usually better off making it an ordinary function. 
E.g. instead of this:


class Food(object):
    @staticmethod
    def spam(x):
        return "spam"
    def ham(self):
        return "%s is a processed meat-like substance" % self.spam()


it is often better to do this:


class Food(object):
    def ham(self):
        return "%s is a processed meat-like substance" % spam()

def spam(x):
    return "spam"



There are exceptions, but you can consider that staticmethod is rarely 
needed. 



-- 
Steven D'Aprano


More information about the Tutor mailing list