Difference Between staticmethod and classmethod in Python
In Python, both staticmethod and classmethod are used to define methods that are associated with a class rather than an instance of the class, but they have key differences in how they behave.
staticmethod:
- Definition: A
staticmethodis a method that does not take any reference to the instance or the class as its first argument. It behaves like a regular function, but it belongs to the class’s namespace. - Usage: It is used when you want a method to be bound to the class, but it does not need access to class or instance-specific data.
- Access: It cannot modify or access the class (
cls) or instance (self) attributes.
Example:
class MyClass:
@staticmethod
def greet(name):
return f"Hello, {name}!"
# Usage
print(MyClass.greet("Alice")) # Output: Hello, Alice!
classmethod:
- Definition: A
classmethodis a method that takes a class reference (cls) as its first argument. This allows the method to access or modify class-level attributes and methods, but not instance-level data. - Usage: It is used when you need access to the class itself, such as modifying class-level variables or calling other class methods.
- Access: It can modify the class state, but not the instance state.
Example:
class MyClass:
count = 0
def __init__(self):
MyClass.count += 1
@classmethod
def get_count(cls):
return cls.count
# Usage
obj1 = MyClass()
obj2 = MyClass()
print(MyClass.get_count()) # Output: 2
Key Differences:
- First argument:
staticmethoddoes not takeselforclsas the first argument.classmethodtakesclsas the first argument (reference to the class).
- Purpose:
staticmethodis used for utility functions that don’t need to access the class or instance.classmethodis used when the method needs to operate on or modify the class state.
class MyClass:
@staticmethod
def greet(name):
return f"Hello, {name}!"
# Usage
print(MyClass.greet("Alice")) # Output: Hello, Alice!
class MyClass:
count = 0
def __init__(self):
MyClass.count += 1
@classmethod
def get_count(cls):
return cls.count
# Usage
obj1 = MyClass()
obj2 = MyClass()
print(MyClass.get_count()) # Output: 2
Interview angle
- “When do you use each?” -
@classmethodwhen the method needs the class, which is what makes alternative constructors work under inheritance sinceclsis the actual subclass.@staticmethodwhen it needs neither instance nor class and is simply namespaced. Plain method when it usesself. - “Why does
@classmethodmatter for factories?” -cls(...)constructs the real subclass, soSubclass.from_dict(...)returns aSubclass. Hardcoding the class name in a static method silently returns the base class. - “Is a
@staticmethodever better than a module function?” - only for discoverability, when it’s conceptually tied to the class. There’s no technical advantage.