1

Since a class or instance method in Python doesn't require you to use cls or self in the method, why can't you just create a class/instance method in place of a static method? Is there an advantage of using a static method as opposed to a class/instance method without referencing the cls/self in the method code?

For example: This class method

@classmethod
def add(cls, num1,num2)
    return num1 + num2

As opposed to this static method

@staticmethod
def add(num1, num2)
    return num1 + num2
Amol Garg
  • 11
  • 2
  • 2
    Why clutter your function signature with parameters you won't use? Your intuition is right in that static methods don't make a lot of sense to have in Python, where you can just have a function. They mostly exist because other object oriented languages have them, so it's easy to translate patterns from those languages to Python. (I think, if someone knows more about the history of this stuff please correct me) – Patrick Haugh Jun 13 '18 at 01:16
  • Maybe this will help: https://stackoverflow.com/questions/136097/what-is-the-difference-between-staticmethod-and-classmethod-in-python?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – U13-Forward Jun 13 '18 at 01:21
  • 1
    Other than `__new__` (which is automatically a `staticmethod` without specifying it), the most common reason to use `staticmethod` is to use the "class attribute as default value" idiom for a callback function value. If you don't `staticmethod` it, the default function will get turned into a bound instance method, which you don't want; with `staticmethod`, it gets turned into a "bound static method", which is just the function itself, with nothing bound in. – abarnert Jun 13 '18 at 01:28
  • 1
    Actually, I suspect the most common reason to use `staticmethod` is actually not understanding Python, and not realizing that (unlike, say, Java) you can have plain old functions, rather than having to create a useless class full of useless `@staticmethod`s to act as a poor substitute for a submodule full of functions… but the best _good_ reason is probably the default-callback thing. – abarnert Jun 13 '18 at 01:32
  • 1
    @abamert, Is there a link to see an example of this callback you are describing? – Reblochon Masque Jun 13 '18 at 01:34

0 Answers0