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
selforcls.
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
@staticmethoddecorator, which makes the method expect aselfparameter. - Including
selforclsas 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
| Concept | Description | Example |
|---|---|---|
| @staticmethod | Decorator to define a static method | @staticmethod |
| No self or cls | Static methods do not take instance or class as first argument | def method(): ... |
| Call via class or instance | Static methods can be called using class or object | ClassName.method() or obj.method() |
| No access to instance data | Cannot use self or instance variables inside static method | Use 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.