Python Classes and Static Methods
Understanding @classmethod and @staticmethod
In Python, most methods you define inside a class are instance methods. They work with a specific object and can access or change its data. But sometimes, you want a method that works with the class itself, or a method that doesn't need to know about the class or any object at all. This is where class methods and static methods come in.
This article will show you what they are, how to use them, and when to choose each one.
What Is a Class Method?
A class method is a method that works with the class itself, not just with one object. You define a class method using the @classmethod decorator. The first parameter of a class method is always cls, which refers to the class (just like self refers to the object in instance methods).
Syntax:
class MyClass:
    @classmethod
    def my_class_method(cls, ...):
        # code that uses cls
        passExample: Factory Method Class methods are often used to create objects in different ways (called "factory methods").
class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    @classmethod
    def from_birth_year(cls, name, birth_year):
        current_year = 2024
        age = current_year - birth_year
        return cls(name, age)
# Create a Dog using the class method
puppy = Dog.from_birth_year("Buddy", 2022)
print(puppy.name, puppy.age)  # Output: Buddy 2- from_birth_yearis a class method. It uses- clsto create a new- Dogobject.
- You can call a class method on the class itself or on an object.
What Is a Static Method?
A static method is a method that belongs to a class, but doesn't need to know anything about the class or any object. It's just a function placed inside a class for organization. You define a static method using the @staticmethod decorator. It does not take self or cls as its first parameter.
Syntax:
class MyClass:
    @staticmethod
    def my_static_method(...):
        # code that does not use self or cls
        passExample: Utility Function Static methods are useful for helper functions related to the class, but that don't need to access or change class or object data.
class MathTools:
    @staticmethod
    def add(a, b):
        return a + b
print(MathTools.add(3, 5))  # Output: 8- addis a static method. It doesn't use- selfor- cls.
- You can call a static method on the class or on an object.
Instance Methods vs. Class Methods vs. Static Methods
| Type | First Parameter | Can Access/Modify Instance? | Can Access/Modify Class? | |-----------------|----------------|----------------------------|--------------------------| | Instance Method | self | Yes | No | | Class Method | cls | No | Yes | | Static Method | (none) | No | No |
- Instance methods: Use self, work with object data.
- Class methods: Use cls, work with class data or create objects.
- Static methods: No selforcls, just grouped with the class for convenience.
When to Use Each Type
- Use an instance method when you need to access or change data on a specific object.
- Use a class method when you need to access or change class-level data, or when you want to provide alternative ways to create objects.
- Use a static method for utility functions that make sense to keep with the class, but don't need to access or change any class or object data.
Common Beginner Mistakes
- Forgetting to add clsas the first parameter of a class method (orselffor instance methods).
- Trying to use selfin a static method (it won't work).
- Using a static method when you actually need to access class or object data.
Example of a mistake:
class Example:
    @classmethod
    def broken(cls):
        print(self)  # ERROR: 'self' is not defined in a class methodSummary
- Use @classmethodfor methods that need the class (cls) as their first parameter.
- Use @staticmethodfor methods that don't needselforcls.
- Choose the right type based on what your method needs to do.
- All three can be called on the class or on an object, but only instance methods can access object data.