Home > front end >  Idiomatic way of calling a static method
Idiomatic way of calling a static method

Time:05-31

What is the pythonic way to call a static method from within the class?

class SomeClass:
    @staticmethod
    def do_something(x: int) -> int:
        return 2*x   17

    def foo(self) -> None:
        print(self.do_something(52))      # <--- this one?
        print(SomeClass.do_something(52)) # <--- or that one?

CodePudding user response:

This depends entirely on your use case since in the context of subclassing, these two approaches do different things. Consider the following:

class OtherClass(SomeClass):
    @staticmethod
    def do_something(x: int) -> int:
        return 42

OtherClass().foo()

This will print 42 and 121 since self.do_something(52) uses the enter image description here

     class SomeClass:
       @staticmethod
       def do_something(x: int) -> int:
         return 2*x   17

       def foo(self) -> None:
          print(SomeClass.do_something(52)) # <--- or that one?
  • Related