What is the difference between class methods and static methods in Python?
· Category: Python Programming
Short answer
Instance methods take self and operate on object state. @classmethod takes cls and operates on the class itself, often used as alternative constructors. @staticmethod takes neither and behaves like a plain function namespaced under the class.
Steps
- Use instance methods for behavior that depends on object attributes.
- Use
@classmethodwhen you need to create instances in different ways or modify class state. - Use
@staticmethodfor utility functions that logically belong to the class but need no class or instance data.
class Person:
species = "Homo sapiens"
def __init__(self, name):
self.name = name
def greet(self):
return f"Hello, I am {self.name}"
@classmethod
def anonymous(cls):
return cls("Anonymous")
@staticmethod
def is_adult(age):
return age >= 18
p = Person.anonymous()
print(p.greet())
print(Person.is_adult(20))
Tips
@classmethodis the right choice for alternative constructors (e.g.,from_json,from_tuple).@staticmethodimproves discoverability and grouping compared to module-level functions.- Both can be called on the class or an instance, but calling on an instance does not pass
selfimplicitly.
Common issues
- Using
@staticmethodwhen you actually need access toclsorselfcauses errors. - Overusing
@classmethodfor behavior that should be in__init__makes the API harder to follow. - Inheritance with
@classmethodpasses the actual subclass ascls, which is usually desired but can be surprising.