Search code examples
pythonstatic-methodsclass-method

python: When to use static method over class method?


Based on what I read, class methods are largely the same as static methods with a few exceptions but have the advantage of providing a class pointer.

As a result, is there really any reason to use static methods over class methods if a non-instance method is defined within a class?

Edit: Since some of you are quick to dismiss this as a duplicate to another question. This is not a question on the difference between the class and static methods. Rather, it is a question on how to decide between the two in the vast majority of cases when their functionality overlap.

Edit #2: The reason I ask is that I am refactoring some existing code from other people. Specifically, there are child classes that share the same modules as the parent and I intend to move them to separate modules. When that occurs, references to out-of-class constants within static methods need to be fixed. I can accomplish that with one of the following ways 1. Import all the constants from the parent module 2. Move all the constants to within parent class and change all the child static methods to class methods 3. Add the "ParentClass." before each reference to the constants

I personally want to do #2 because it avoids namespace contamination and this is also why I asked this question. It's a question of style mostly. Hope this provides enough context.


Solution

  • Almost always, actually. You rarely need access to the class object that is passed automatically to a class method. Python class methods (which should not be compared to class methods in a language like Java) are primarily intended to be used to provide alternate constructors.

    Specifically, a class method would look something like

    @classmethod
    def my_class_method(cls, foo):
       ...
    

    If you never actually use cls in the body of the method, you might first change it to

    @staticmethod
    def my_static_method(foo):
       ...
    

    Next, you might consider whether my_static_method actually needs to be part of the class and whether it could be a standalone function instead.

    If you do use cls, then obviously it needs to be a class method.