Python classmethod vs staticmethod

09 Feb 2014

classmethod must have a reference to a class object as the first parameter, whereas staticmethod can have no parameters at all.

classmethod are for when you need to have methods that aren’t specific to any particular instance, but still involve the class in some way. The most interesting thing about them is that they can be overridden by subclasses. Factory methods (alternative constructors) are indeed a classic example of class methods.

If you have a class MyClass, and a module-level function that operates on MyClass (factory, dependency injection stub, etc), make it a classmethod.

Here is some code example:

class Date(object):

    day = 0
    month = 0
    year = 0

    def __init__(self, day=0, month=0, year=0): = day
        self.month = month
        self.year = year

    def is_date_valid(date_as_string):
        day, month, year = map(int, date_as_string.split('-'))
        return day <= 31 and month <= 12 and year <= 3999

    def from_string(cls, date_as_string):
        day, month, year = map(int, date_as_string.split('-'))
        date1 = cls(day, month, year)
        return date1

day, month, year = map(int, string_date.split('-'))
date1 = Date(day, month, year)
date2 = Date.from_string('11-09-2012')

if is_date_valid('11-09-2012'):
    print 'Valid Day!'

Pay attention to cls parameter in the example above; cls is an object that holds class itself, not an instance of the class. It’s pretty cool because if we inherit our Date class, all children will have from_string defined also.

staticmethod doesn’t have any access to what the class is- it’s basically just a function, called syntactically like a method, but without access to the object and it’s internals (fields and another methods), while classmethod does.

So staticmethod is similar to C++ or Java’s static methods, which can be called without creating an instance of a class.

stackoverflow thread