3.6 - Class Methods and Static Methods
3.6.1 - Introduction to Class Methods
Class methods in Python are methods that are bound to the class rather than its objects. They can access and modify the class state across all instances of the class. Class methods are defined using the @classmethod
decorator.
Example 1: Basic Class Method
class MyClass:
counter = 0
def __init__(self):
MyClass.counter += 1
@classmethod
def instances_created(cls):
return f"Total instances created: {cls.counter}"
# Create instances
obj1 = MyClass()
obj2 = MyClass()
print(MyClass.instances_created()) # Output: Total instances created: 2
Example 2: Using Class Methods for Factory Functions
class Date:
def __init__(self, day=0, month=0, year=0):
self.day = day
self.month = month
self.year = year
@classmethod
def from_string(cls, date_as_string):
day, month, year = map(int, date_as_string.split('-'))
return cls(day, month, year)
date = Date.from_string('11-09-2012')
print(date.day, date.month, date.year) # Output: 11 9 2012
3.6.2 - Introduction to Static Methods
Static methods in Python are methods that belong to a class but don't need a class or instance reference. They are defined using the @staticmethod
decorator and are used for utility functions that perform a task in isolation.
Example 1: Basic Static Method
class MathUtils:
@staticmethod
def add(x, y):
return x + y
print(MathUtils.add(5, 7)) # Output: 12
Example 2: Static Methods with No Class State
class TemperatureConverter:
@staticmethod
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32
@staticmethod
def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5/9
print(TemperatureConverter.celsius_to_fahrenheit(0)) # Output: 32.0
print(TemperatureConverter.fahrenheit_to_celsius(32)) # Output: 0.0
3.6.3 - Differences and Use Cases
Understanding the differences and appropriate use cases for class methods and static methods is crucial:
-
Class Methods: Use class methods when the method requires access to the class itself or needs to modify class state. They are often used for factory methods that create class instances in different ways.
-
Static Methods: Use static methods when the functionality you are implementing is related to the class's purpose but does not require class or instance data. They are useful for utility or helper functions.
3.6.4 - Combining Class and Static Methods
In practice, a class can have both class methods and static methods, each serving its specific purpose.
Example: Combined Use of Class and Static Methods
class Circle:
pi = 3.14159
def __init__(self, radius):
self.radius = radius
@classmethod
def from_diameter(cls, diameter):
radius = diameter / 2
return cls(radius)
@staticmethod
def area(radius):
return Circle.pi * radius ** 2
circle1 = Circle(5)
circle2 = Circle.from_diameter(10)
print(circle1.area(circle1.radius)) # Output: 78.53975
print(circle2.area(circle2.radius)) # Output: 78.53975