Python: Class Methods vs Static Methods

Introduction

To continue this review of Object Oriented Programming (OOP), this post will cover the topic of class methods vs static methods. The importance of these concepts emphasizes the same simplicity that OOP offers. In understanding these basic decorators, you will be able to write cleaner and more readable code moving forward. This article will be dealing with the theory behind each, the proper syntax and also a quick example. Let’s dive in.

Class Methods

A class method takes in the class as the first argument instead of the instance, most often denoted as “self”. If this is new information, you might want to check out my last post before continuing. Class methods can modify all instances of a class. A common usage of class methods allows the user to modify a class variable that is then applicable to all instances of that class.

Another common usage for class methods are as alternative constructors. This essentially means that you allow yourself multiple ways of creating objects. Check out this example:

The above class method might be particularly useful if that format was how you were consistently receiving data. You might also want different class methods for different data formats. By doing this, you ensure cleaner, simpler and more efficient code.

Static Methods

Static methods are interesting in that they cannot modify the class state or any instance state. In other words, static methods refer to functions that do not include any mention of a class or class instance. Therefore, a static method does not take in the class or the instance as an argument. The questions becomes why you might want to use this type of method. The use-case for static methods is far more infrequent than class methods, but they are certainly helpful. Say you wanted to check if it was a game day for the NFL. You don’t need any of our class information to accomplish this, but it is related to the class. To keep it simple, we will simple check if today is one of three typical game days: Monday, Thursday or Sunday.

Conclusion

I will continue to post about OOP topics in the coming days and weeks. To reiterate just once more, OOP is universally applicable in the land of programming, and it is a necessary skill for all those who haven’t yet had the opportunity to pick it up. My plan is to use it in the building of a simple stock trading bot, and it will allow me to keep my code and overall structure very minimalistic. The general applications, however, are limitless. Happy coding!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store