What is the difference between @staticmethod and @classmethod?

Technology CommunityCategory: PythonWhat is the difference between @staticmethod and @classmethod?
VietMX Staff asked 3 years ago

staticmethod is a method that knows nothing about the class or instance it was called on. It just gets the arguments that were passed, no implicit first argument. It’s definition is immutable via inheritance.

class C:
    @staticmethod
    def f(arg1, arg2, ...): ... 

classmethod, on the other hand, is a method that gets passed the class it was called on, or the class of the instance it was called on, as first argument. Its definition follows Sub class, not Parent class, via inheritance.

class C:
   @classmethod
   def f(cls, arg1, arg2, ...): ...  

If your method accesses other variables/methods in your class then use @classmethod.