1

I was writing a function earlier when my linter recommended I made the method static. I've always used staticmethods without really knowing what they're for or why they're useful, besides from I can't access any attributes of the current class (since there's no self)

I was just wandering, is there any advantage doing this

class Foo:
    @staticmethod
    def bar():
        return "bazz"

over just doing

class Foo:
    def bar(self):
        return "bazz"

Thank you.

Nexy7574
  • 514
  • 1
  • 5
  • 10

1 Answers1

1

At least the calling of static method does not require to pass a "self" parameter, so - yes, it has an advantage.

Andrii Shvydkyi
  • 2,236
  • 1
  • 14
  • 19
  • 2
    Can you explain more about how not needing to add "self" in the argument list is an advantage? It's 4 characters of typing less. But you need to add the "@staticmethod" annotation at the top so it's a net gain of characters. – cs95 Jan 04 '21 at 10:26
  • The value of the "self" parameter should be passed to every method call so additional space is required for it in every stack frame. I don't think that it can have a drastic performance impact but in some cases, the increase of stack consumption may be meanful. Especially for the recursions. – Andrii Shvydkyi Jan 04 '21 at 16:46