How to Define Static Method in Python

Pavol Kutaj
1 min readJul 26, 2022

--

The aim of this page📝 is to define how static methods can be defined in Python. Let’s create a _generate_serial() function that will generate a new serial number in a small class for shipping containers. The name static method is an anachronism in Python — it refers to the keyword used to indicate the equivalent in older languages (C,C++,C#, etc.)

  • In other words, how can we associate _generate_serial() with the class, not with the instance of the class?
  1. use @staticmethod decorator
  2. do not sign the static method with self
  3. use the class prefix for accessing Class attributes
  4. use the class prefix for calling static methods
  • not just that static methods are used across the whole class — in python, static methods have no direct knowledge even about the class itself, even when they are defined within one
  • they simply allow us to group a function within the class block when the function is conceptually related to the class

--

--

No responses yet