Search code examples
pythonclasspython-3.xstatic-methodsclass-method

Why use classmethod instead of staticmethod?


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?


Solution

  • 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.