staticmethod decorator seems pointless

I was reading about the @staticmethod in Python when I came across tge following code:

class MyClass:
    my_var = 0

    def static_method():
        MyClass.my_var += 1

I just don’t understand exactly why you can write a code like this… Doesn’t it defeat the purpose of this method to be static?

I get it that there’s also the fact that the first parameter won’t be a class/instance reference, but… Still weird to call this decorator like that if I still can access class variables, no?

And if I can access class variables, why everywhere I read about it says that I cannot, even though I just clearly did with the code above? Is it just because I’m doing it wrong?

>Solution :

The idea that a static method can’t modify class state is based on the idea that the static method doesn’t receive a reference to the class as an argument like a class method does. However, in this case, a reference to the class is provided as a hard-coded value.

One reason for defining a static method rather than a class method is to guarantee that you modify the attribute of a specific class, rather than a possible subclass.

class A:
   my_var = 0

   def foo(cls):
       cls.my_var += 1

   def bar():
       A.my_var += 1

class B(A):
    my_var = 0

A call to will modify B.my_var, not A.my_var. A call to will modify A.my_var.

Leave a Reply