Python instance method vs static method, which one to use on when?

By | April 11, 2019

I have been writing python OO for a while and every time when I create a method, I always ask myself, should this be instance method or staticmethod (or classmethod)?

As you might already aware that the difference between instance method and static method is that static method doesn’t have access to the instance, same goes with class method which only has access to the class.

At first, I thought an instance method can turn into a static method if I pass all the necessary parameters, right?! It’s easier to write unit tests against a static method since I don’t have to prepare an instance.

There were times I started with static methods and then having the need to call another static method, but the inner static method need to access a variable that is not relevant to the outer static method, so I had to pass that variable into the outer static method, sounds code smell isn’t it?!

The performance between the 2 is negligible, so deciding the 2 is mostly OO design issue.

So I have come up some simple rules to decide when to create instance method or static method:

  1. if the method is likely to call other methods (or instance methods), better be on the safe side, use instance method
  2. if the method is very thin(great cohesion), or unlikely to call other methods, use static method
  3. if the method alters the instance state, use instance method

Please let me know what you think by leaving a comment.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.