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

  1. Use instance methods for behavior that depends on object attributes.
  2. Use @classmethod when you need to create instances in different ways or modify class state.
  3. Use @staticmethod for 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

  • @classmethod is the right choice for alternative constructors (e.g., from_json, from_tuple).
  • @staticmethod improves 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 self implicitly.

Common issues

  • Using @staticmethod when you actually need access to cls or self causes errors.
  • Overusing @classmethod for behavior that should be in __init__ makes the API harder to follow.
  • Inheritance with @classmethod passes the actual subclass as cls, which is usually desired but can be surprising.