1

I am wondering what is, if any, the best practice regarding class and static methods.

Consider the follwoing class

class A:
    number = 0

    @classmethod
    def add_int_m(cls, m: int) -> int:
        return cls.number + m

    @staticmethod
    def add_int_k(k: int) -> int:
        return A.number + k

The two give the same result, but is one approach preferred over the other?

user101
  • 476
  • 1
  • 4
  • 9
  • This [post](https://stackoverflow.com/questions/136097/what-is-the-difference-between-staticmethod-and-classmethod) might be relevant to you. – Pierre Nov 02 '19 at 23:05
  • Honestly, `@staticmethod` is mostly a style/organizational thing. I rarely see it in the wild unless someone coming from a language like Java or C# starts writing Python code... – juanpa.arrivillaga Nov 02 '19 at 23:15

1 Answers1

1

If you're using class variables, you definitely want to use @classmethod, and NOT @staticmethod. Imagine class B extends class A:

class A:
    number = 0

    @classmethod
    def add_int_m(cls, m: int) -> int:
        return cls.number + m

    @staticmethod
    def add_int_k(k: int) -> int:
        return A.number + k

class B(A):
    pass


B.number = 10

B.add_int_m(1)  # returns 11
B.add_int_k(1)  # returns 1

The staticmethod add_int_k still uses the variable of class A.

Bober
  • 479
  • 3
  • 6