Member-only story

Understanding classmethod vs staticmethod in Python

Allwin Raju
2 min readDec 9, 2024

--

Python offers two powerful decorators, @classmethod and @staticmethod, to define methods with specific use cases that differ from regular instance methods. Let’s explore their differences, usage, and see some examples.

Read for free: https://allwin-raju.medium.com/understanding-classmethod-vs-staticmethod-in-python-87f53baa94f0?sk=399c3e4e0b4418eb0756357daf43488e

1. @classmethod

A class method is bound to the class and not the instance. It receives the class (cls) as its first parameter, allowing it to access class attributes and methods.

Use Cases:

  • Factory methods for creating instances.
  • Accessing or modifying class-level data.

Example:

class MyClass:
class_variable = "class-level data"

@classmethod
def class_method(cls):
return f"Accessing {cls.class_variable} from {cls}"

# Call without creating an instance
print(MyClass.class_method())

# Output: Accessing class-level data from <class '__main__.MyClass'>

2. @staticmethod

A static method is bound to neither the instance nor the class. It behaves like a regular function but belongs to the class’s namespace. It doesn’t take…

--

--

No responses yet