Class Methods & Static Methods
Overview
Not all logic inside a class belongs to an individual instance. @classmethod takes the Class itself (cls) as its first argument and can modify global class state; they are most often used as 'Alternative Constructors'. @staticmethod takes neither self nor cls. It is completely disconnected from the class and instance state; it's simply a utility function that logically belongs inside the class's namespace for organizational purposes.
Syntax
class Date:
def __init__(self, year, month, day):
self.date = f"{year}-{month}-{day}"
# Class Method: Operates on the Class, great for factories
@classmethod
def from_string(cls, date_str):
year, month, day = date_str.split("-")
# cls() is equivalent to Date()
return cls(year, month, day)
# Static Method: Just a standard function housed in the class
@staticmethod
def is_valid_format(date_str):
return len(date_str) == 10 and date_str.count("-") == 2
# Using the class method to create an object from a string
my_date = Date.from_string("2023-10-31")
# Using the static method directly on the class
print(Date.is_valid_format("2023-10-31")) # TrueCommon Pitfalls
- Using a standard instance method (with
self) when you never actually access any instance attributes. A good IDE/Linter will yell at you to convert it to a@staticmethodfor a slight performance boost and cleaner design.
Interview Questions
@classmethod in Python?They are heavily used as 'Factory Methods' to provide alternative constructors. For example, if __init__ takes integers, a @classmethod can parse a JSON string or CSV row, format the data, and return a new instance.
Real-World Example
Keeping a global tally of how many instances have been created across the entire program.
class Employee:
# Class attribute
total_employees = 0
def __init__(self, name):
self.name = name
Employee.total_employees += 1
@classmethod
def get_headcount(cls):
# Accesses the class attribute directly
return cls.total_employeesCheck Your Knowledge
Test your understanding of Class Methods & Static Methods with these quick questions.