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.

class Player:

performance_incentive = 0.15

def __init__(self, first, last, team, pay):
self.first = first
self.last = last
self.team = team
self.pay = pay

def apply_raise(self):
self.pay = int(self.pay * self.performance_incentive)
@classmethod
def set_performance_incentive(cls, incentive):
cls.performance_incentive = incentive
player_1 = Player('Tom','Brady', 'Buccaneers', 25000000)
player_2 = Player('Aaron','Rodgers', 'Packers', 20000000)
# Can call this method either of the following 2 ways, but using class is most likely the most readable optionPlayer.set_performance_incentive(0.3) or player_1.set_performance_incentive(0.3)print(Player.performance_incentive)
print(player_1.performance_incentive)
print(player_2.performance_incentive)
Output:
0.2
0.2
0.2

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:

class Player:

def __init__(self, first, last, team, pay):
self.first = first
self.last = last
self.team = team
self.pay = pay

@classmethod
def from_string(cls, player_str):
first, last, team, pay = player_str.split('-')
return cls(first, last, team, pay)
player_string = 'Isaiah-Wilson-Dolphins-10000000'# Now a new instance can be created using the class method from_string
player_3 = Player.from_string(player_string)

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.

import datetime
from datetime import date
class Player:

def __init__(self, first, last, team, pay):
self.first = first
self.last = last
self.team = team
self.pay = pay


@staticmethod
def is_workday():
today = date.today()
if today.weekday() == 0 or today.weekday() == 3 or today.weekday() == 6:
return 'Gameday!'
else:
return 'No Games Today...'
Player.is_workday()# Output (because today is a Monday):
'Gameday!'

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!

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How I Created The Folder Sniper

An Approach to Live2D Viseme Rigging

Best Chatbot Developer Certification Course

LRU Cache: An Introduction and Implementation in Go

Connect Mendix with REST-DB for Backup

How to calculate CHURN with SQL

ICTurtles Launch Review

“The Balls” NFT’s as a Utility Asset: What’s in store for you?

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
Michael Wirtz

Michael Wirtz

More from Medium

Mutable vs Immutable Objects in Python

Explain Function in Python

Object-oriented Programming in Python — Lesson 1. Substitutability and Inheritance

Python Timeit Module