Static and Class Methods

Introduction

Python provides two special types of methods: static methods and class methods. These methods allow us to define behaviors at the class level rather than the instance level.

In this tutorial, we will cover:

  1. What static methods and class methods are
  2. The @staticmethod and @classmethod decorators
  3. Differences between instance, static, and class methods
  4. Real-world examples of when to use static and class methods

1. Instance Methods vs. Static Methods vs. Class Methods

FeatureInstance MethodClass MethodStatic Method
Requires self?YesNoNo
Requires cls?NoYesNo
Can access instance variables?YesNoNo
Can modify class variables?NoYesNo
Belongs toObjectClassClass

2. Static Methods in Python (@staticmethod)

A static method is a method that does not depend on instance or class variables. It is simply a function that belongs to a class but does not access or modify class or instance attributes.

Defining a Static Method

A static method is defined using the @staticmethod decorator.

class MathOperations:
    @staticmethod
    def add(a, b):
        return a + b

# Calling the static method
print(MathOperations.add(10, 20))  # Output: 30

Since add() does not use self or cls, it is a static method.

When to Use Static Methods?

When a method performs a task independent of class or instance attributes
For utility functions (e.g., math operations, data conversions)


3. Class Methods in Python (@classmethod)

A class method is a method that works on the class level and can access or modify class variables. It takes cls as its first parameter instead of self.

Defining a Class Method

A class method is defined using the @classmethod decorator.

class Employee:
    company = "Dynamic Duniya"  # Class variable

    @classmethod
    def set_company(cls, new_name):
        cls.company = new_name  # Modifying class attribute

# Before modification
print(Employee.company)  # Output: Dynamic Duniya

# Changing company name
Employee.set_company("Tech Innovators")
print(Employee.company)  # Output: Tech Innovators

The class method set_company() modifies the class variable company.

When to Use Class Methods?

When you need to modify class attributes
For alternative constructors (creating objects in different ways)


4. Real-World Examples

Example 1: Static Method for Utility Function

class Temperature:
    @staticmethod
    def celsius_to_fahrenheit(celsius):
        return (celsius * 9/5) + 32

print(Temperature.celsius_to_fahrenheit(25))  # Output: 77.0

The method converts temperature and does not use instance or class variables, making it a static method.


Example 2: Class Method for Alternative Constructor

Class methods can be used to create objects in multiple ways.

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def from_string(cls, student_str):
        name, age = student_str.split("-")
        return cls(name, int(age))

# Creating student object using a string
s1 = Student.from_string("Amit-21")
print(s1.name, s1.age)  # Output: Amit 21

The from_string() class method allows us to create a Student object from a formatted string.


5. Summary

Static methods (@staticmethod): Do not use self or cls, used for utility functions
Class methods (@classmethod): Use cls, modify class variables, useful for alternative constructors
Instance methods: Use self, operate on individual objects