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.
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.
Static methods are useful when you want to:
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.
Python Static methods can be created in two ways. Let’s see each of the ways here:
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.
@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.
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.
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.
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.
@staticmethod
decoratorOne 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
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.
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 |
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 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.
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.
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)
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
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")
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)
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.
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.
Why are you adding the numbers in the first example?
- A Discord User#4063
What does w.r.t mean?
- Mike
Thanks …! Wonderful explanation.
- Shweta
Good explanation! But the method is called multiplyNums, but, actually, it is summing the numbers?!
- WA
good explanation
- himanshu
@staticmethod line also the program is same output
- nag
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
Amazing explanation
- BitchBark