Class Methods and Static Methods
Besides regular instance methods, classes can have two other types of methods that change how self is handled.
1. Class Methods (@classmethod)
- Decorated with
@classmethod. - Takes
cls(conventionally) as its first argument, referring to the class itself, not the instance. - Used for factory methods (alternative constructors) or methods that deal with class-level attributes.
python class Settings: DEFAULT_THEME = 'dark'
@classmethod
def get_default_theme(cls):
# cls refers to the Settings class
return cls.DEFAULT_THEME
Accessing via class, not instance
print(Settings.get_default_theme()) # Output: dark
2. Static Methods (@staticmethod)
- Decorated with
@staticmethod. - Takes no required
selforclsargument. - They are utility functions grouped within a class because they logically belong to the class, but they do not interact with either the class attributes or instance attributes.
python class MathUtility: @staticmethod def add_numbers(a, b): return a + b
Called directly via the class name
print(MathUtility.add_numbers(10, 5)) # Output: 15