Main Content

Defining static methods in Python

Archive - Originally posted on "The Horse's Mouth" - 2010-08-05 19:57:26 - Graham Ellis

If you define a method within a class, it defaults to being a dymanic method - in other words, one which runs on an object that's a member of the class. If you want to define a method that applies to the class as a whole, you're looking for a static or class method - and in Python you can set one of those up by using the same syntax as as dynaic method, and then calling a modifier function (staticmethod or classmethod). Or you can use a decorator of the same name.

Here's the "modifier" way:

def geticecream():
    return "It's melted"
geticecream = staticmethod(geticecream)


And the "decorator" way:

@staticmethod
def getnutsandjuice():
    return "odd combo!"


Full source (from the course earlier this week) [here].