4

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?

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. Commented Jun 25, 2020 at 13:53
  • If this function would only ever be called on Stock objects, then it makes sense to leave it as shown. Commented Jun 25, 2020 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 Commented Jun 25, 2020 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. Commented Jun 25, 2020 at 14:02

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.