Q15: What are the differences between @staticmethod and @classmethod?

  • @classmethod: Receives implicit class binding (cls) as first parameter. Can access/modify class state and acts as alternative constructors.
  • @staticmethod: Isolated utility function bound to class namespace. Receives no implicit self or cls arguments.
Classmethod Factory Pattern
class Date:
    def __init__(self, day, month, year):
        self.day, self.month, self.year = day, month, year
        
    @classmethod
    def from_string(cls, date_str):
        day, month, year = map(int, date_str.split('-'))
        return cls(day, month, year) # Alternative factory constructor
💡 classmethod acts as a factory constructing instances from alternate string formats.
Key Takeaways
  • @classmethod receives cls binding; ideal for alternative factory constructors.
  • @staticmethod receives no implicit binding; ideal for utility functions.
Knowledge Check

Which decorator receives the class itself (cls) as its first implicit parameter?