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:

ClassName.StaticFunctionName()

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):
		self.name = name
		self.school = school
		self.grades = []
	
	def add_grade(self, grade):
		self.grades.append(grade)
	
	def give_average(self):
		return sum(self.grades) / len(self.grades)
	
	def say_name(self):
		return self.name
	
	def say_hi(self):
		print("Hello!!!!")

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:

[...]
@staticmethod
def say_hi():
	print("Hello!!!!")

This allows us to do write code like this:

s = Student("Laura","MIT")
s.add_grade(56)
s.add_grade(76)
s.give_average()

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

# From the class itself
Student.say_hi()