-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.

2
  • What about when the function is static, or when it is a method attached to a class... Commented Oct 18, 2017 at 15:38
  • You never really need to use staticmethod not classmethod, although, classmethod is actually useful sometimes Commented Oct 18, 2017 at 15:53

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.