Appearance
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:
Create a static method in Python, using the staticmethod in Python
python
class MyClass:
@staticmethod
def static_method():
# Method code goes here
pass
<div class="alert alert-info flex not-prose">Watch a video course Python - The Practical Guide
</div>
You can then call the static method on the class itself, like this:
Call a static method in Python
python
MyClass.static_method()Alternatively, you can also call the static method on an instance of the class, like this:
Call the static method on an instance of the class in Python
python
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.