Question
In Python, can I define a static method that can be called directly on the class, like this?
MyClass.the_static_method()
If so, how do static methods work, and how are they different from regular instance methods?
Short Answer
By the end of this page, you will understand what a static method is in Python, how to define one with @staticmethod, and how to call it on a class or an instance. You will also see how static methods differ from instance methods and class methods, and when they are a good design choice.
Concept
In Python, a static method is a method defined inside a class that does not automatically receive either:
- the instance (
self) - the class (
cls)
That means it behaves much like a regular function, but it is placed inside the class because it is logically related to that class.
You define a static method using the @staticmethod decorator:
class MyClass:
@staticmethod
def the_static_method():
print("Hello from a static method")
Then you can call it directly on the class:
MyClass.the_static_method()
You can also call it on an instance:
obj = MyClass()
obj.the_static_method()
Why this matters
In real programs, not every function inside a class needs access to object state. Sometimes you want:
- a helper function related to the class
- validation logic
- formatting or conversion logic
- utility behavior grouped with the class for organization
Static methods help you keep related code together without pretending the method needs self or cls.
The key idea
If a method needs:
- instance data → use an instance method
- class-level data → use a class method
- neither → use a static method
Mental Model
Think of a class as a toolbox.
- An instance method is a tool that needs a specific toolbox item to work on, so it receives
self. - A class method is a tool that needs to know which toolbox it belongs to, so it receives
cls. - A static method is just a useful tool stored in the toolbox drawer. It does not need the toolbox or any item from it to work.
So a static method is like a calculator kept inside a "MathTools" box. The calculator belongs there logically, but it does not need the box itself to do addition.
Syntax and Examples
The basic syntax is:
class MyClass:
@staticmethod
def greet(name):
return f"Hello, {name}!"
Call it on the class:
print(MyClass.greet("Ava"))
Output:
Hello, Ava!
You can also call it on an instance:
obj = MyClass()
print(obj.greet("Liam"))
Example: grouping utility logic inside a class
class Temperature:
@staticmethod
def celsius_to_fahrenheit(c):
return (c * 9 / 5) + 32
print(Temperature.celsius_to_fahrenheit(25))
Output:
77.0
This method does not use self or cls. It simply performs a calculation that is related to temperature, so placing it inside the Temperature class makes organizational sense.
What happens if you forget @staticmethod
Without the decorator, Python treats the method as an instance method:
class MyClass:
def greet(name):
return f"Hello, {name}!"
MyClass.greet("Ava")
This may behave differently than expected because methods defined in a class are normally descriptors, and instance calls will try to pass self automatically. If your method is meant to receive no self, @staticmethod makes that intent explicit and safe.
Step by Step Execution
Consider this example:
class MathHelper:
@staticmethod
def add(a, b):
return a + b
result = MathHelper.add(3, 4)
print(result)
Step by step:
- Python reads the
MathHelperclass definition. - It sees the
@staticmethoddecorator aboveadd. - Python stores
addas a static method on the class. MathHelper.add(3, 4)is called.- No
selforclsis passed automatically. - The values
3and4are passed directly intoaandb. - The method returns
7. print(result)outputs:
7
Compare with an instance method
class MathHelper:
def add(self, a, b):
return a + b
obj = MathHelper()
print(obj.add(3, 4))
Here is what changes:
objis created.obj.add(3, 4)automatically passesobjasself.- So the method receives three values internally:
self,a, andb.
That automatic binding is exactly what a static method avoids.
Real World Use Cases
Static methods are useful when behavior belongs with a class conceptually, but does not need instance or class state.
Common examples
- Validation helpers
- checking whether an email format is valid
- checking whether a password meets rules
- Conversion utilities
- Celsius to Fahrenheit
- kilometers to miles
- string to normalized slug
- Parsing helpers
- splitting a log line
- cleaning user input
- Domain-specific utility functions
- tax calculation rules
- scoring formulas
- date formatting helpers
Example: validation
class UserValidator:
@staticmethod
def is_valid_username(username):
return len(username) >= 3 and username.isalnum()
print(UserValidator.is_valid_username("sam123"))
Example: formatting
class ReportFormatter:
@staticmethod
def title_case(text):
return text.title()
print(ReportFormatter.title_case("monthly sales report"))
Real Codebase Usage
In real projects, developers often use static methods in small, focused ways.
Common patterns
Helper methods inside a class
A class may contain small utility functions that support the main behavior.
class PriceCalculator:
@staticmethod
def apply_tax(amount, rate):
return amount * (1 + rate)
Validation before object creation
class User:
def __init__(self, username):
if not self.is_valid_username(username):
raise ValueError("Invalid username")
self.username = username
@staticmethod
def is_valid_username(username):
return len(username) >= 3
This keeps validation logic close to the class.
Parsing or normalization
class Product:
@staticmethod
def normalize_name(name):
return name.strip().lower()
Guarding against unnecessary state access
If a method does not use self, making it static signals that clearly to other developers.
A practical guideline
If you write a method and notice:
- it never uses
self - it never uses
cls - it is only relevant to this class
then @staticmethod is often a good fit.
If it starts needing class or instance data later, convert it to the appropriate method type.
Common Mistakes
1. Forgetting the @staticmethod decorator
Broken example:
class MyClass:
def hello(name):
return f"Hello, {name}"
obj = MyClass()
print(obj.hello("Ava"))
Why it fails:
objis automatically passed as the first argument- Python tries to use
objasname - the arguments no longer match what you intended
Fix:
class MyClass:
@staticmethod
def hello(name):
return f"Hello, {name}"
2. Using a static method when you actually need self
Broken example:
class Counter:
def __init__(self):
self.value = 0
@staticmethod
def increment():
self.value += 1
Why it fails:
- static methods do not receive
self selfis undefined here
Fix: use an instance method
class Counter:
def __init__(self):
self.value = 0
def increment(self):
self.value += 1
3. Using a static method when you actually need cls
Broken example:
class Animal:
species = "Unknown"
@staticmethod
def get_species():
return cls.species
Why it fails:
- static methods do not receive
cls
Fix: use a class method
class Animal:
species = "Unknown"
@classmethod
def get_species(cls):
return cls.species
4. Putting too many unrelated utilities in a class
A static method should still be logically connected to the class. If not, a standalone function may be clearer.
Bad design:
class User:
@staticmethod
def calculate_circle_area(radius):
return 3.14 * radius * radius
This works technically, but it does not belong in User.
Comparisons
| Method type | First parameter | Can access instance data? | Can access class data? | Typical use |
|---|---|---|---|---|
| Instance method | self | Yes | Yes, through class/instance | Behavior tied to one object |
| Class method | cls | Not directly | Yes | Alternative constructors, class-wide behavior |
| Static method | None automatic | No | No | Utility logic related to the class |
Example comparison
class Example:
class_value = 10
def instance_method(self):
return self.class_value
@classmethod
def class_method(cls):
return cls.class_value
@staticmethod
def static_method(x, y):
return x + y
Static method vs standalone function
| Choice | Use when |
|---|---|
| Static method | The function is strongly related to the class concept |
| Standalone function | The function is general-purpose and not tied to one class |
A static method is mostly about organization and intent, not special access to object data.
Cheat Sheet
class MyClass:
@staticmethod
def my_method(arg1, arg2):
return arg1 + arg2
Call forms:
MyClass.my_method(1, 2)
obj = MyClass()
obj.my_method(1, 2)
Rules
- Use
@staticmethodfor methods that need neitherselfnorcls - Static methods can be called on:
- the class
- an instance
- Static methods do not get automatic first arguments
- If you need instance state, use an instance method
- If you need class state, use a class method
Quick decision guide
- Needs object data? →
def method(self): - Needs class data? →
@classmethod - Needs neither? →
@staticmethod
Related syntax
class MyClass:
def instance_method(self):
pass
@classmethod
def class_method(cls):
pass
@staticmethod
def static_method():
pass
FAQ
Can I call a static method directly on a Python class?
Yes. That is one of its main uses.
MyClass.the_static_method()
Can I call a static method on an instance too?
Yes. Python allows both:
obj = MyClass()
obj.the_static_method()
Does a static method receive self automatically?
No. A static method receives no automatic first argument.
When should I use @staticmethod in Python?
Use it when the method belongs logically to the class but does not need instance data or class data.
What is the difference between @staticmethod and @classmethod?
@staticmethodgets no automatic argument@classmethodreceivescls, the class itself
Should I use a static method or a normal function?
If the logic is closely related to a class, a static method can improve organization. If it is general-purpose, a regular function is often better.
Can a static method access class variables?
Not automatically. It can still refer to the class by name explicitly, but if the behavior depends on the class itself, @classmethod is usually the better design.
Mini Project
Description
Build a small utility class for text processing. This project demonstrates how static methods can group related helper functions inside a class without needing object state. It mirrors real code where formatting and validation helpers are kept close to the domain they support.
Goal
Create a TextTools class with static methods that clean, format, and validate strings.
Requirements
- Create a class named
TextTools - Add a static method that trims whitespace from a string
- Add a static method that converts text to lowercase
- Add a static method that checks whether a string is empty after trimming
- Call the static methods directly on the class and print the results
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Add Rows to a Pandas DataFrame in Python
Learn how to add rows to a Pandas DataFrame, why repeated row appends are slow, and when to use loc, concat, or record lists.
Call a Function by Name in a Python Module
Learn how to call a function by name in a Python module using strings, getattr, and safe patterns for dynamic function dispatch.