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
.
Asked
Active
Viewed 168 times
-3

Willem Van Onsem
- 443,496
- 30
- 428
- 555

Dhanasekaran Anbalagan
- 2,524
- 1
- 16
- 12
-
What about when the function is *static*, or when it is a method attached to a *class*... – Willem Van Onsem Oct 18 '17 at 15:38
-
You never really *need* to use `staticmethod` not `classmethod`, although, `classmethod` is actually useful sometimes – juanpa.arrivillaga Oct 18 '17 at 15:53
1 Answers
1
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.

blue_note
- 27,712
- 9
- 72
- 90