-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
  • 443,496
  • 30
  • 428
  • 555
Dhanasekaran Anbalagan
  • 2,524
  • 1
  • 16
  • 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
  • 27,712
  • 9
  • 72
  • 90