How to Create Static Methods in Python?

Better Stack Team
Updated on June 19, 2024

In Python, a static method is a method that belongs to a class but does not operate on instances of that class. Unlike instance methods, static methods do not have access to the instance (self) or class (cls) variables. They are defined using the @staticmethod decorator.

Here's how you can define and use static methods in Python:

class MyClass:
    # Static method definition using @staticmethod decorator
    def static_method():
        print("This is a static method")

# Calling the static method using the class name

In this example:

  • static_method() is defined within the MyClass class and decorated with @staticmethod.
  • Static methods do not require a reference to an instance (e.g., self) or the class itself (e.g., cls) as their first parameter.
  • You can call a static method using the class name, as shown with MyClass.static_method().

Static methods are often used for utility functions that are related to the class but do not depend on specific instance data. They can be called without creating an instance of the class.

It's important to note that while static methods are associated with a class, they cannot access or modify class or instance variables directly. They are primarily used for organizing code within a class namespace and for providing utility functions.

Got an article suggestion? Let us know
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github