Python: Static Functions

Python: Static Functions

How to do Static Functions in Python

Static Functions

In object oriented languages we don’t always have to instantiate a class to an object to use its functions. To do that we use static functions in a class. So in this way we can access to that functionality via:


In Python we realize this by using a decorator. In technical terms a decorator allows us to run code before and after a function the decorator is used on. But in this case @staticmethod decorator allows us to facilitate this usage:

class Student:
	def __init__(self, name, school): = name = school
		self.grades = []
	def add_grade(self, grade):
	def give_average(self):
		return sum(self.grades) / len(self.grades)
	def say_name(self):
	def say_hi(self):

In this super not-realistic example we can see that the say_hi function is not really related to any parameters in the class and won’t change depending on the class values. So we can implement it as a static method:

def say_hi():

This allows us to do write code like this:

s = Student("Laura","MIT")

# Static function usage
# From the instantiated object
s.say_hi() # Because it is still a Student class

# From the class itself