Python & FastAPI•Part 2: Python Core Language, Internals & Runtime (6 - 25)
`@staticmethod` vs `@classmethod` vs Instance Methods:
In Simple Words:
- Instance method: Takes
self; accesses and mutates instance state. @classmethod: Takescls; accesses class state; ideal for alternative factory constructors.@staticmethod: Takes neitherselfnorcls; acts as an isolated pure function inside a class namespace.
python
class Date:
def __init__(self, year, month, day):
self.year, self.month, self.day = year, month, day
@classmethod
def from_string(cls, date_str): # Factory constructor
y, m, d = map(int, date_str.split("-"))
return cls(y, m, d)
@staticmethod
def is_valid_year(year):
return 1900 <= year <= 2100