@classmethod and @staticmethod
Define class-level and static methods with appropriate decorators.
Introduction
@classmethod receives the class as first argument. @staticmethod receives nothing special. Both are defined on the class.
Instance vs Class vs Static
Regular methods get self. Class methods get cls. Static methods get neither. Choose based on what data you need.
class Demo:
def instance(self): return 'instance'
@classmethod
def class_m(cls): return f'class: {cls.__name__}'
@staticmethod
def static_m(): return 'static'
d = Demo()
print(d.instance())
print(Demo.class_m())
print(Demo.static_m())All lessons in this course
- Functions as First-Class Objects
- Writing Custom Decorators
- The @property Decorator
- @classmethod and @staticmethod