Class and Static Methods in Python

Loading

Python provides two types of special methods that operate differently from instance methods:

  1. Class Methods – Work with the class rather than instances
  2. Static Methods – Independent of instance and class

Both are defined using decorators:

  • @classmethod → Used for class methods
  • @staticmethod → Used for static methods

1. Class Methods (@classmethod)

What is a Class Method?

A class method works with the class itself instead of a specific instance. It can modify class-level attributes but cannot access instance-specific data.

Key Points:

✅ Takes cls (class reference) as the first parameter
✅ Modifies class attributes, not instance attributes
✅ Can be called on both the class and instances


1.1 Defining and Using a Class Method

class Car:
manufacturer = "Toyota" # Class attribute

def __init__(self, model, year):
self.model = model # Instance attribute
self.year = year # Instance attribute

@classmethod
def set_manufacturer(cls, name):
cls.manufacturer = name # Modifies class attribute

@classmethod
def from_string(cls, car_string):
model, year = car_string.split("-")
return cls(model, int(year))

# Modifying class attribute using class method
Car.set_manufacturer("Honda")
print(Car.manufacturer) # Output: Honda

# Creating an instance using class method
car1 = Car.from_string("Civic-2022")
print(car1.model, car1.year) # Output: Civic 2022

Why use a class method?

  • set_manufacturer(cls, name) changes the class-level manufacturer attribute for all instances.
  • from_string(cls, car_string) is an alternative constructor that creates an object from a string.

2. Static Methods (@staticmethod)

What is a Static Method?

A static method is independent of both instance and class. It is similar to a regular function but placed inside a class for organization.

Key Points:

✅ Does not take self or cls as parameters
✅ Cannot modify instance (self) or class (cls) attributes
✅ Used for utility/helper functions that belong logically to the class


2.1 Defining and Using a Static Method

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

@staticmethod
def multiply(a, b):
return a * b

# Calling static methods
print(MathOperations.add(3, 5)) # Output: 8
print(MathOperations.multiply(4, 6)) # Output: 24

Why use a static method?

  • add() and multiply() perform operations without modifying class or instance attributes.
  • These methods belong to the class but do not depend on instance-specific data.

3. Class Methods vs. Static Methods vs. Instance Methods

FeatureClass Method (@classmethod)Static Method (@staticmethod)Instance Method
Takes self? No No Yes
Takes cls? Yes No No
Accesses instance attributes? No No Yes
Accesses class attributes? Yes No Yes
Modifies class attributes? Yes No Yes
Modifies instance attributes? No No Yes
Use caseAlternative constructors, modifying class-level attributesUtility/helper functions, independent logicRegular methods that operate on instance data

4. Real-World Example: Employee Management System

class Employee:
raise_percentage = 1.05 # Class attribute

def __init__(self, name, salary):
self.name = name # Instance attribute
self.salary = salary # Instance attribute

def apply_raise(self):
self.salary *= self.raise_percentage # Uses class attribute

@classmethod
def set_raise_percentage(cls, percentage):
cls.raise_percentage = percentage # Modifies class attribute

@staticmethod
def is_working_day(day):
return day.lower() not in ["saturday", "sunday"]

# Creating employee instances
emp1 = Employee("Alice", 50000)
emp2 = Employee("Bob", 60000)

# Changing raise percentage using class method
Employee.set_raise_percentage(1.10)

# Applying new raise percentage
emp1.apply_raise()
emp2.apply_raise()
print(emp1.salary) # Output: 55000.0
print(emp2.salary) # Output: 66000.0

# Checking working day using static method
print(Employee.is_working_day("Monday")) # Output: True
print(Employee.is_working_day("Sunday")) # Output: False

Why use a class method?

  • set_raise_percentage(cls, percentage) modifies a class-level attribute (raise_percentage).
  • The new raise percentage applies to all employees.

Why use a static method?

  • is_working_day(day) does not depend on any instance or class data.
  • It provides utility functionality related to the class.

5. When to Use Class and Static Methods?

Use Class Methods (@classmethod) when:

  • You need to work with class attributes instead of instance attributes.
  • You want to create alternative constructors (from_string()).
  • You want to apply changes at the class level (set_raise_percentage()).

Use Static Methods (@staticmethod) when:

  • You don’t need to access instance (self) or class (cls) attributes.
  • The method is a utility/helper function related to the class.
  • The method performs a generic operation (is_working_day()).

6. Summary

FeatureClass MethodStatic MethodInstance Method
Decorator@classmethod@staticmethodNone
First Parametercls (class)No required parameterself (instance)
Can modify class attributes? Yes No Yes
Can modify instance attributes? No No Yes
Common Use CasesAlternative constructors, modifying class-level attributesUtility functions, independent logicWorking with instance data

Class methods work at the class level and modify class attributes.
Static methods are utility functions that do not modify class or instance attributes.
Instance methods work on individual objects and modify instance attributes.

Leave a Reply

Your email address will not be published. Required fields are marked *