0
0
PythonHow-ToBeginner · 3 min read

How to Create Static Method in Python: Simple Guide

In Python, you create a static method by adding the @staticmethod decorator above a method inside a class. Static methods do not receive the instance (self) or class (cls) as the first argument and behave like regular functions inside the class namespace.
📐

Syntax

To create a static method, place the @staticmethod decorator above the method inside a class. The method should not have self or cls parameters.

  • @staticmethod: Marks the method as static.
  • method_name(): The function name without self or cls.
python
class MyClass:
    @staticmethod
    def my_static_method():
        print("This is a static method")
💻

Example

This example shows a class with a static method that prints a message. You can call it using the class name or an instance.

python
class Calculator:
    @staticmethod
    def add(a, b):
        return a + b

# Call static method using class
result1 = Calculator.add(5, 7)
print(result1)  # Output: 12

# Call static method using instance
calc = Calculator()
result2 = calc.add(10, 20)
print(result2)  # Output: 30
Output
12 30
⚠️

Common Pitfalls

Common mistakes when creating static methods include:

  • Forgetting the @staticmethod decorator, which makes the method expect a self parameter.
  • Including self or cls as parameters, which static methods do not accept.
  • Trying to access instance or class variables inside a static method, which is not possible without passing them explicitly.
python
class WrongExample:
    def no_decorator(self):  # Missing @staticmethod and should have self if instance method
        print("This will cause an error if called on instance")

    @staticmethod
    def wrong_params(self):  # Static method should not have self
        print("Incorrect parameter")

# Correct way
class RightExample:
    @staticmethod
    def correct_method():
        print("This works fine")
📊

Quick Reference

ConceptDescriptionExample
@staticmethodDecorator to define a static method@staticmethod
No self or clsStatic methods do not take instance or class as first argumentdef method(): ...
Call via class or instanceStatic methods can be called using class or objectClassName.method() or obj.method()
No access to instance dataCannot use self or instance variables inside static methodUse parameters to pass data

Key Takeaways

Use @staticmethod decorator to create a static method inside a class.
Static methods do not receive self or cls parameters.
Call static methods using the class name or an instance.
Static methods cannot access instance or class variables directly.
Always include @staticmethod decorator to avoid errors.