Class Methods in Python
In Python, class methods are methods that are bound to the class rather than its objects. They can modify the class state that applies across all instances of the class, and they are defined using the @classmethod
decorator.
Key Features of Class Methods:
- Decorator: Class methods are marked with the
@classmethod
decorator. - First Parameter: The first parameter of a class method is
cls
, which refers to the class itself. This allows access to class attributes and methods. - Access: Class methods can be called on the class itself or on instances of the class.
- Use Case: They are typically used for factory methods that return an instance of the class or when you want to modify class-level attributes.
Example of Class Methods
This example demonstrates the use of class methods in a Python class.
Code Example
class Employee:
raise_amount = 1.04 # Class variable
def __init__(self, name, salary):
self.name = name
self.salary = salary
@classmethod
def set_raise_amount(cls, amount):
cls.raise_amount = amount # Modify the class variable
@classmethod
def from_string(cls, emp_str):
name, salary = emp_str.split('-')
return cls(name, float(salary)) # Create an instance from a string
# Creating an instance of Employee
emp1 = Employee("John", 50000)
# Accessing class method to set a new raise amount
Employee.set_raise_amount(1.05)
# Creating an instance using the class method
emp_str = "Jane-60000"
emp2 = Employee.from_string(emp_str)
print(f"Employee 1: {emp1.name}, Salary: {emp1.salary}, Raise Amount: {Employee.raise_amount}")
print(f"Employee 2: {emp2.name}, Salary: {emp2.salary}, Raise Amount: {Employee.raise_amount}")
Output
Employee 1: John, Salary: 50000, Raise Amount: 1.05
Employee 2: Jane, Salary: 60000.0, Raise Amount: 1.05
Employee 2: Jane, Salary: 60000.0, Raise Amount: 1.05
Conclusion
Class methods provide a way to manipulate class-level data and functionality that applies to all instances of a class. They are especially useful for factory methods and maintaining consistent class attributes.