avatarSamer Sallam

Summary

The provided content is an article that explains static methods in Python Object-Oriented Programming, detailing their purpose, syntax, and usage within a class without needing access to instance or class attributes.

Abstract

The article is part of a complete course on Object-Oriented Programming in Python and focuses on static methods. It begins with an introduction to the concept of static methods, emphasizing their role when a method is logically related to a class but does not require access to the class or instance attributes. The author explains the syntax for creating static methods using the @staticmethod decorator and illustrates their practical application with examples, including a Student class scenario. The article also provides a comparison with other method types, such as instance and class methods, and concludes with a summary of the key points about static methods, reinforcing the idea that they are used for utility functions or operations that are self-contained and do not interact with the state of the class or its instances.

Opinions

  • The author suggests that static methods are useful for defining utility functions that are logically connected to a class but do not need to modify or access the class's or object's state.
  • It is implied that a clear understanding of static methods can enhance the design of a class by allowing the inclusion of methods that perform operations independent of class or instance data.
  • The article conveys the opinion that static methods contribute to better code organization by grouping related functionality under a class namespace, even if those functions do not operate on instance or class data.
  • The author encourages the reader to practice defining and using static methods by providing a concrete example and inviting them to follow along with the course material available on GitHub and other linked resources.
  • There is an underlying opinion that mastering static methods is an essential step in becoming proficient in Python's object-oriented programming paradigm.
  • The author emphasizes the importance of proper naming conventions for static methods, suggesting that all letters should be lowercase and underscores used for multiple words.
  • The article subtly promotes the benefits of Medium membership, suggesting that readers can support the author and gain access to a wealth of educational content by subscribing.

Static Methods: Python OOP Complete Course — Part 6

Photo by Max Vakhtbovych on Pexles

Before we start let me tell you that:

  • This article is a part of The Complete Course in Object Oriented Programming in Python which you can find it here.
  • All resources are available in the “Resources” section below.
  • This article is also available as a YouTube video here.

Introduction

So far, you have learned how to add methods and attributes on the class level which are class attributes and class methods and on the object level which are instance attributes and instance methods. But what if you want to define a method that does need access neither to the object nor to the class itself? Let us see in this article. So…

This article will cover the following outlines:

  1. Attributes Types and Methods Types Reminder
  2. Static Methods
  3. Static Methods Syntax

1. Attributes Types and Methods Types Reminder

Photo by ThisIsEngineering on Pexles

So far, we have learned about the two types of attributes and two types of methods which are:

  • Instance Attributes
  • Class Attributes
  • Instance Methods
  • Class Methods

This article is focusing on the last type of methods that you will learn about in this course which is

  • Static Methods

(If you like to remember the Instance Attributes and Instance Methods article, Just click here). (If you like to remember the Class Attributes and Class Methods article, Just click here).

Let us learn about static methods and in which context you have to define a static method.

2. Static Methods

Static Methods are the methods that have a logical connection to the class itself, but they don’t need access to neither instance attributes nor class attributes.

Photo by Lidiia Nemyrova on Unsplash

So, why do I have to define a method that doesn’t have any access to any of the attributes?

Simply, sometimes you have methods that are just logically connected to this class even if it doesn’t need this access to any of those attributes.

A common example of static methods is if you want to define some utility functions under one class, and these functions are usually used as helpful functions for the work of other class methods or other classes.

The question now is, how we can create a static method?

3. Static Methods Syntax

To create a static method:

  • First of all, we define a class and give it a name ClassName.
  • This method is defined using the keyword def as a normal function in Python and gives the method a name.
  • After that, you can use as many as you want of positional arguments, and arbitrary arguments.
  • For static methods, we use the decorator “@static method”, where this decorator will convert your method from a normal instance method into a static method.
class ClassName:
    @staticmethod
    def static_method1(arg1,…, argn, *args, **kwargs):
      # do something logically related to the class
    @staticmethod
    def static_method2(arg1,…, argn, *args, **kwargs):
        # do something logically related to the class

As usual, don’t forget to use the colon after your function definition to avoid a syntax error.

Note:

  • The first parameter for this method is not (self: the instance) or (cls: the class) which means that this method doesn’t have any access to the class state “class attributes” ( any information related to the class itself) or to the object state “instance attributes” ( any information related to the object itself)
  • Remember it does something logically related to the class.
  • Finally, you can list as many as you wish of static methods and let them do something logically related to the class according to your use case.
Photo by Branimir76 on Pexles

Going back to the Student example which has been implemented in the previous articles. Where it has

  1. Multiple class and instance attributes.
  2. One instance and two class methods, as follows:
from datetime import datetime
class Student:
    num_undergraduates = 0
    num_ postgraduates = 0
    undergraduates_age_range = range(19, 24)
    postgraduates_age_range = range(24, 30)
    def __init__(self, _id, first_name, last_name, age):
       self.id = _id
       self.first_name = first_name
       self.last_name = last_name
       self.full_name = self.first_name + " " + self.last_name
       self.age = age
       if self.age in Student.undergraduates_age_range:
          Student.num_undergraduates += 1
      elif self.age in Student.postgraduates_age_range:
           Student.num_postgraduates += 1
      else:
          raise Exception('Invalid Age')
      self.classes = []
  def enrol(self, class_name):
      print(self.full_name)
      self.classes.append(class_name)
  @classmethod
  def get_undergraduates_percentage(cls):
      num_students = cls.num_undergraduates + cls.num_postgraduates
      return cls.num_undergraduates / num_students
@classmethod
 def create_student_from_birthday(cls, student_id, first_name,
     last_name,birthday):
     age = round((datetime.now() - birthday).days / 365)
     return cls(student_id, first_name, last_name, age)

Assume we need a method that would return true if the student is passed and return false if the student isn’t passed according to his/her CGPA.

If you think about this method you will figure out that this method does not need any access to either instance attributes or class attributes, it is just logically related to your class.

Now, let us add this method:

  • Define a new method which is a static method (using the decorator @staticmethod) and its name is_passed.
  • This method takes the student’s CGPA as an argument, in case this CGPA is greater than 50 it returns True (passed) otherwise it returns False (failed) (refer to the last method in the next example).

Solution Input:

from datetime import datetime
class Student:
    num_undergraduates = 0
    num_ postgraduates = 0
    undergraduates_age_range = range(19, 24)
    postgraduates_age_range = range(24, 30)
    def __init__(self, _id, first_name, last_name, age):
       self.id = _id
       self.first_name = first_name
       self.last_name = last_name
       self.full_name = self.first_name + " " + self.last_name
       self.age = age
       if self.age in Student.undergraduates_age_range:
          Student.num_undergraduates += 1
       elif self.age in Student.postgraduates_age_range:
            Student.num_postgraduates += 1
       else:
         raise Exception('Invalid Age')
       self.classes = []
   def enrol(self, class_name):
      print(self.full_name)
      self.classes.append(class_name)
  @classmethod
  def get_undergraduates_percentage(cls):
      num_students = cls.num_undergraduates + cls.num_postgraduates
      return cls.num_undergraduates / num_students
@classmethod
  def create_student_from_birthday(cls, student_id, first_name,
      last_name,birthday):
     age = round((datetime.now() - birthday).days / 365)
     return cls(student_id, first_name, last_name, age)
@staticmethod
def is_passed(cgpa):
    if cgpa > 50:
       return True
    else:
       return False

Keep in mind that when you name your static method all the letters should be small, and we use underscore if there are more than two words.

Till now the static method has been defined but has not been called yet.

So let us try to call this method, simply to call it, you just need to:

  • Define the variable cgpa.
  • Use the class name Student.the_method_name
  • Pass the method’s parameters

Solution Input:

cgpa = 30
if Student.is_passed(cgpa):
    print('Passed')
else:
    print('Failed')

Output

Failed

We got Failed as a result because in this case, cgpa is less than 50 which means this student is not passed.

Now, let us try to replace 30 with 55…

Solution Input:

cgpa = 55
if Student.is_passed(cgpa):
    print('Passed')
else:
    print('Failed')
print()

Output

Passed

Great job, now you are familiar with all attributes and methods types.

Now, let us summarize what we have learned in this article:

Photo by Ann H on pexels
  • Static Methods are the methods that have a logical connection to the class, but they don’t need access to neither instance attributes nor class attributes.
  • To define a static method, we define it as any normal method in Python, but we use the decorator “@static method”. Refer to Figure 1.
Figure 1: Static methods summary (Image By Author).
  • Do not forget the colon when you define your functions. Otherwise, you will get a syntax error.

P.S.: A million thanks for your time reading my story. Before you leave let me mention quickly two points:

  • First, to get my posts in your inbox directly, would you please subscribe here, and you can follow me here.
  • Second, writers made thousands of $$ on Medium. To get unlimited access to Medium stories and start earning, sign up now for Medium membership, which only costs $5 per month. By signing up with this link, you can directly support me at no extra cost to you.

To get back to the previous article, you can use the following link:

Part 5:Class Attributes and Class Methods

To move on to the next article, you can use the following link:

Part 7:Property in Python

Resources:

Object Oriented
Python
Programming
Static Methods
Oop Concepts
Recommended from ReadMedium