I like to know when I need to use staticmethod or classmethod decorators.
can you please guide me simple code, so that can understand usage of
staticmethod and classmethod.
1 Answer
When you call a method of a python object, the object itself is automatically passed as the first parameters (usually named self)
You can change this in two ways
- annotate with
@classmethod: now, instead of the object, the class of the object is automatically passed as first argument - annotate with
@staticmethod: now, no extra argument is passed, just the ones you provided. Just like a normal python function
Classmethods are commonly used for alternative constructors. Static methods are plain functions that are put inside the class namespace, just for logical grouping.
staticmethodnotclassmethod, although,classmethodis actually useful sometimes