-3

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.

Willem Van Onsem
  • 397,926
  • 29
  • 362
  • 485
Dhanasekaran Anbalagan
  • 2,346
  • 1
  • 14
  • 12

1 Answers1

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
  • 25,410
  • 6
  • 56
  • 79