CARVIEW |
- Log in to:
- Community
- DigitalOcean
- Sign up for:
- Community
- DigitalOcean

By Shubham and Anish Singh Walia

Python static method
In this quick post, we will learn how to create and use a Python static method. We will also have a look at what advantages and disadvantages static methods offer as compared to the instance methods. Let’s get started.
What is a static method?
Static methods in Python are extremely similar to python class level methods, the difference being that a static method is bound to a class rather than the objects for that class. This means that a static method can be called without an object for that class. This also means that static methods cannot modify the state of an object as they are not bound to it. Let’s see how we can create static methods in Python.
Why and when to use static methods
Static methods are useful when you want to:
- Group utility functions together in a class that logically belong together
- Create methods that don’t need access to instance attributes or methods
- Implement functionality that belongs conceptually to a class but doesn’t require an instance
- Write helper methods that operate on class attributes rather than instance attributes
- Organize namespace and improve code readability by keeping related functions in one class
- Create factory methods that can return different instances of the class based on parameters
- Perform operations that are related to the class but don’t need to access or modify class state
- Avoid creating unnecessary instances when you just need to call a function
Static methods are particularly common in utility classes, factory pattern implementations, and for operations that are conceptually related to a class but don’t depend on instance-specific data.
Creating python static methods
Python Static methods can be created in two ways. Let’s see each of the ways here:
Using staticmethod()
Let’s directly jump to sample code snippet on how to use the staticmethod()
approach:
class Calculator:
def addNumbers(x, y):
return x + y
# create addNumbers static method
Calculator.addNumbers = staticmethod(Calculator.addNumbers)
print('Product:', Calculator.addNumbers(15, 110))
Note that we called the addNumbers we created without an object. When we run this program, here is the output we will get: There were no surprises there. This approach is controlled as at each place, it is possible to create a static method out of a class method as well. Let’s see another approach with the same example here.
Using @staticmethod
This is a more subtle way of creating a Static method as we do not have to rely on a statement definition of a method being a class method and making it static at each place you make it static. Let’s use this annotation in a code snippet:
class Calculator:
# create addNumbers static method
@staticmethod
def addNumbers(x, y):
return x + y
print('Product:', Calculator.addNumbers(15, 110))
When we run this program, here is the output we will get: This was actually a much better way to create a static method as the intention of keeping the method static is clear as soon as we create it and mark it with the
@staticmethod
annotation.
Advantages of Python static method
Static methods have a very clear use-case. When we need some functionality not w.r.t an Object but w.r.t the complete class, we make a method static. This is pretty much advantageous when we need to create Utility methods as they aren’t tied to an object lifecycle usually. Finally, note that in a static method, we don’t need the self
to be passed as the first argument. API Reference: Python Documentation.
Practical Use Cases
Grouping utility functions inside a class namespace
Static methods are particularly useful for grouping utility functions that are related to a class but don’t require access to class or instance state. This approach helps to keep the namespace clean and organized, making it easier to understand and use the class. For example, consider a StringUtilities
class that provides various string manipulation methods. You might define a static method strip_punctuation
to remove punctuation from a string, as it’s a utility function that doesn’t depend on any class or instance state.
class StringUtilities:
@staticmethod
def strip_punctuation(input_string):
# Implementation to remove punctuation from the input string
pass
By using a static method, you can call StringUtilities.strip_punctuation
without creating an instance of the class, making it a convenient utility function.
Creating reusable logic that’s logically tied to a class but doesn’t need class or instance state
Static methods are ideal for creating reusable logic that is conceptually tied to a class but doesn’t require access to class or instance state. This is particularly useful when you need to perform operations that are related to the class but don’t depend on instance-specific data. For instance, consider a MathUtilities
class that provides mathematical operations. You might define a static method calculate_factorial
to calculate the factorial of a number, as it’s a mathematical operation that doesn’t rely on any class or instance state.
class MathUtilities:
@staticmethod
def calculate_factorial(number):
# Implementation to calculate the factorial of the input number
pass
By using a static method, you can call MathUtilities.calculate_factorial
without creating an instance of the class, making it a reusable piece of logic that’s tied to the class conceptually.
Common Errors and Debugging
Forgetting to use @staticmethod
decorator
One common error is forgetting to use the @staticmethod
decorator when defining a static method. This can lead to confusion and errors, as the method will not be recognized as static without the decorator. For example, consider the following incorrect implementation:
class Calculator:
def addNumbers(x, y):
return x + y
In this case, addNumbers
is not a static method because it’s missing the @staticmethod
decorator. To fix this, you would add the decorator as follows:
class Calculator:
@staticmethod
def addNumbers(x, y):
return x + y
Confusing static methods with class methods
Another common mistake is confusing static methods with class methods. While both types of methods are bound to a class, they have different use cases and behaviors. Static methods do not require access to class or instance state, whereas class methods do. Understanding the differences between these two types of methods is crucial for effective use.
For example, consider a Person
class with a static method get_average_age
that calculates the average age of all persons, and a class method get_person_count
that returns the total number of persons. The get_average_age
method doesn’t require access to any instance state, making it a good candidate for a static method. On the other hand, get_person_count
requires access to the class state to count the total number of persons, making it a good candidate for a class method.
class Person:
person_count = 0
@staticmethod
def get_average_age():
# Implementation to calculate the average age of all persons
pass
@classmethod
def get_person_count(cls):
return cls.person_count
By understanding the differences between static and class methods, you can effectively use them to organize your code and avoid common errors.
Comparison charts between method types
Method Type | Use Case | Access to Class State | Access to Instance State |
---|---|---|---|
Static Method | Utility functions | No | No |
Class Method | Factory methods | Yes | No |
Instance Method | Regular methods | Yes | Yes |
Examples
Static Method Example
class MathUtilities:
@staticmethod
def calculate_factorial(number):
# Implementation to calculate the factorial of the input number
pass
In this example, calculate_factorial
is a static method that can be called without creating an instance of the MathUtilities
class. It does not have access to class or instance state.
Class Method Example
class Person:
person_count = 0
@classmethod
def add_person(cls):
cls.person_count += 1
return cls()
In this example, add_person
is a class method that has access to the class state (the person_count
class variable). It does not have access to instance state.
Instance Method Example
class Person:
def __init__(self, name):
self.name = name
def greet(self):
print(f"Hello, my name is {self.name}!")
In this example, greet
is an instance method that has access to instance state (the name
instance variable). It also has access to class state, but it is not shown in this example.
FAQ Section
1. What is a static method in Python?
A static method in Python is a method that belongs to a class rather than an instance of the class. This means it can be called directly on the class itself, without the need to create an instance of the class. Static methods are essentially utility functions that are grouped within a class for organizational purposes.
Example:
class MathUtilities:
@staticmethod
def calculate_factorial(number):
# Implementation to calculate the factorial of the input number
pass
# Calling a static method without creating an instance
MathUtilities.calculate_factorial(5)
2. How is a static method different from a class method?
A static method does not have access to the class or instance state, whereas a class method has access to the class state. This means a static method cannot modify or use class or instance variables, whereas a class method can modify class variables.
Example:
class MyClass:
class_var = "This is a class variable"
@staticmethod
def static_method():
# This method cannot access or modify class_var
pass
@classmethod
def class_method(cls):
# This method can access and modify class_var
cls.class_var = "This is a modified class variable"
pass
3. When should I use a static method in Python?
Use a static method when you need a utility function that is related to a class but does not require access to the class or instance state. This is particularly useful for grouping utility functions that are not specific to an instance but are related to the class.
Example:
class StringUtilities:
@staticmethod
def is_palindrome(s):
# Implementation to check if a string is a palindrome
pass
# Using a static method to check if a string is a palindrome
StringUtilities.is_palindrome("radar")
4. Can a static method access instance variables?
No, a static method cannot access instance variables because it is not bound to an instance of the class. It can only access class variables if they are explicitly passed as arguments.
Example:
class MyClass:
def __init__(self, instance_var):
self.instance_var = instance_var
@staticmethod
def static_method(instance_var):
# This method can access instance_var if it is passed as an argument
pass
# Creating an instance and passing the instance variable to the static method
my_instance = MyClass("This is an instance variable")
MyClass.static_method(my_instance.instance_var)
5. Why use static methods instead of regular functions?
Use static methods instead of regular functions when you want to group utility functions within a class for better organization and readability. This is particularly useful when the utility functions are closely related to the class but do not require access to the class or instance state.
Conclusion
Static methods are a useful tool in Python for organizing utility functions within a class. They are particularly useful for grouping utility functions that are not specific to an instance but are related to the class. They can be created using the @staticmethod
decorator or the staticmethod()
function.
To learn more about Python classes and objects, check out these articles:
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
About the author(s)

Helping Businesses stand out with AI, SEO, & Technical content that drives Impact & Growth | Senior Technical Writer @ DigitalOcean | 2x Medium Top Writers | 2 Million+ monthly views & 34K Subscribers | Ex Cloud Engineer @ AMEX | Ex SRE(DevOps) @ NUTANIX
Still looking for an answer?
Good explanation! But the method is called multiplyNums, but, actually, it is summing the numbers?!
- WA
Actually, this example works even if the @staticmethod decorator is removed. However, if the class had a mixture of static and non-static methods then the decorator would be necessary.
- Ken
- Table of contents
- Python static method
- What is a static method?
- Why and when to use static methods
- Creating python static methods
- Advantages of Python static method
- Practical Use Cases
- Common Errors and Debugging
- Comparison charts between method types
- FAQ Section
- Conclusion
Deploy on DigitalOcean
Click below to sign up for DigitalOcean's virtual machines, Databases, and AIML products.
Become a contributor for community
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
DigitalOcean Documentation
Full documentation for every DigitalOcean product.
Resources for startups and SMBs
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Get our newsletter
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
The developer cloud
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Get started for free
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.