How to Define Static Methods in Python
1 min readAug 23, 2022
- Let’s create a
_generate_serial()
function that will generate a new serial number in a small class generating IDs for shipping containers. - The name static method is an anachronism in Python — it refers to the traditional keyword used to indicate the equivalent in old languages (C,C++,C#, Java, etc.)
- In other words, how can we associate the method with the class (making it “static”) as opposed to associating it with the instance of the class?
- use
@staticmethod
decorator - do not sign the static method with
self
- use the class prefix for accessing Class attributes as in
result = ShippingContainer.next_serial
4. use the class prefix for calling static methods as in
self.serial = ShippingContainer._generate_serial()
- Static methods, however, are not used only across the whole class
- In python, they have no direct knowledge even about the class itself even when they are defined within one
- Static methods simply allow us to group a function within the class block when the function is conceptually related to the class
- Therefore, you could just locate
_generate_serial()
outside of all clases in a global scope and call it from within the class without@staticmethod
decorator - This would be synonymous