Difference between Static method and Class method in Python


In Python, both staticmethod and classmethod are ways to define methods that are tied to a class and not to an instance of the class. However, there are important differences between the two:

First Argument:

Class Method: It takes a reference to the class (cls) as its first parameter. This allows you to call class-level attributes and other class methods or even to instantiate the class. You would generally use cls as the convention for this parameter.
Static Method: It doesn’t take any specific first parameter. It behaves just like a regular function but belongs to the class’s namespace.

Decorator:

Class Method: Defined using the @classmethod decorator.
Static Method: Defined using the @staticmethod decorator.

Usage:

Class Method: Useful when you need to have methods that operate on class-level attributes or when you want to be able to override methods in subclasses.
Static Method: Useful when you want to perform an action in a class’s context but don’t need to access or modify the class or its instances.

Overriding:

Class Method: Can be overridden by subclasses, which allows for polymorphism. The method defined in the subclass will receive the subclass as its cls parameter, not the base class.
Static Method: Cannot be easily overridden for polymorphism. It behaves the same way no matter what subclass you might be working with.

Calling:

Both static methods and class methods can be called on the class itself, rather than on instances of the class.

Here’s a quick example to illustrate:

class MyClass:

class_var = "Class variable"

@classmethod
def class_method(cls):
return f"Called from the class method of {cls}. Accessed: {cls.class_var}"

@staticmethod
def static_method(arg):
return f"Called from the static method with argument: {arg}"



# Usage
print(MyClass.class_method()) # Outputs: Called from the class method of <class '__main__.MyClass'>. Accessed: Class variable
print(MyClass.static_method(5)) # Outputs: Called from the static method with argument: 5

In conclusion:

Use classmethod when you need to interact with class-level attributes or want to be polymorphic with subclasses.
Use staticmethod when you just want to place a method inside a class for organizational reasons, and the method neither needs to access instance-specific data nor class-level data.


Author: robot learner
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source robot learner !
  TOC