Static methods in Python?
In Python, a static method is a method that belongs to a class rather than an instance of the class. It is a method that is shared among all instances of a class.
To create a static method in Python, you can use the @staticmethod
decorator, like this:
class MyClass:
@staticmethod
def static_method():
# Method code goes here
pass
Watch a video course
Python - The Practical Guide
You can then call the static method on the class itself, like this:
MyClass.static_method()
Alternatively, you can also call the static method on an instance of the class, like this:
obj = MyClass()
obj.static_method()
Static methods are useful for creating utility functions that are related to a class, but that don't need access to any class-specific state. They are also a good way to define methods that you don't want to be overridden by subclasses.