InterviewHubPRO
Section Overview
Q19

Question 19 of 65

Part 2: Python Core Language, Internals & Runtime (6 - 25)

29%
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: Takes cls; accesses class state; ideal for alternative factory constructors.
  • @staticmethod: Takes neither self nor cls; 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