3

When should I use static methods and functions? Let me provide a current example. I have a class that holds stock data, and one of my static methods in the class is as follows:

class Stock:
    @staticmethod
    def percent_change(old, new):
        return ((new - old) / old) * 100

Would it make more sense to just create the static method as a function outside of the class? As it stands, I need to call percent_change on a Stock object, but if I created a function outside of the class, I could just call the function by itself. Any thoughts?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
commonelk
  • 63
  • 4
  • 1
    Somewhat of an opinion-based question, but in general, prefer a function unless you can make a strong argument for why your code would be improved by making a static method instead. – chepner Jun 25 '20 at 13:53
  • If this function would only ever be called on `Stock` objects, then it makes sense to leave it as shown. – John Gordon Jun 25 '20 at 13:53
  • Static methods can be used to group some utility function together with a class, like the one you have.Have a look here [link](https://stackoverflow.com/questions/2438473/what-is-the-advantage-of-using-static-methods-in-python) – MOHAMMED NUMAN Jun 25 '20 at 13:58
  • I see. I think it might make sense to keep it as a static method for now because the only class I have so far is the Stock class, so I'd only call the method on Stock objects anyways. Thank you. – commonelk Jun 25 '20 at 14:02

0 Answers0