Why use classmethod instead of staticmethod?

Question:

I know what they do and I’ve seen many examples of both, but I haven’t found a single example where I would have to use classmethod instead of replacing it with a staticmethod.

The most common example of classmethod I’ve seen is for creating a new instance of the class itself, like this (very simplified example, there’s no use of the method atm. but you get the idea):

class Foo:
    @classmethod
    def create_new(cls):
        return cls()

This would return a new instance of Foo when calling foo = Foo.create_new().
Now why can’t I just use this instead:

class Foo:
    @staticmethod
    def create_new():
        return Foo()

It does the exact same, why should I ever use a classmethod over a staticmethod?

Asked By: Patrik Lippojoki

||

Answers:

There’s little difference in your example, but suppose you created a subclass of Foo and called the create_new method on the subclass…

class Bar(Foo):
    pass

obj = Bar.create_new()

…then this base class would cause a new Bar object to be created…

class Foo:
    @classmethod
    def create_new(cls):
        return cls()

…whereas this base class would cause a new Foo object to be created…

class Foo:
    @staticmethod
    def create_new():
        return Foo()

…so the choice would depend which behavior you want.

Answered By: Aya

Yes, those two classes would do the same.

However, now imagine a subtype of that class:

class Bar (Foo):
    pass

Now calling Bar.create_new does something different. For the static method, you get a Foo. For the class method, you get a Bar.

So the important difference is that a class method gets the type passed as a parameter.

Answered By: poke

From the docs, a class method receives its class as an implicit argument, while static methods are unaware of the class in which they reside.

This can be useful in situations where you have an inherited static method that you want to override with different behaviour in the subclass.

Answered By: dckrooney