Class Methods & Static Methods
Python has three kinds of methods in a class: instance methods (most common), class methods (bound to the class), and static methods (utility functions).
Instance vs Class vs Static
class MyClass:
class_var = "shared"
def instance_method(self):
# has access to self (instance) and cls
return f"instance: {self.class_var}"
@classmethod
def class_method(cls):
# has access to cls (the class itself), not self
return f"class: {cls.class_var}"
@staticmethod
def static_method(x, y):
# no self, no cls — just a regular function in the namespace
return x + yClass Methods as Alternative Constructors
class Date:
def __init__(self, year, month, day):
self.year = year; self.month = month; self.day = day
@classmethod
def from_string(cls, date_str):
y, m, d = map(int, date_str.split("-"))
return cls(y, m, d)
@classmethod
def today(cls):
from datetime import date
d = date.today()
return cls(d.year, d.month, d.day)
d = Date.from_string("2024-05-15")
print(d.year, d.month, d.day) # 2024 5 15Static Method Use Case
class MathHelper:
@staticmethod
def is_prime(n):
if n < 2: return False
return all(n % i != 0 for i in range(2, int(n**0.5)+1))
print(MathHelper.is_prime(17)) # True