Python staticmethod() Function
The staticmethod()
function converts a regular function into a static method of a class
Syntax
staticmethod(function)
staticmethod()
is considered an un-Pythonic way of creating a static function. So, in newer versions of Python, you can use the @staticmethod
decorator.
Syntax of @staticmethod is:
@staticmethod
def func(args, ...)
staticmethod() Parameters
Python staticmethod()
function parameters:
Parameter | Condition | Description |
---|---|---|
function | Required | function that needs to be converted to a static method |
staticmethod() Return Value
Python staticmethod()
function returns a static method for a function passed as the parameter.
Examples
Example 1: Create a static method using staticmethod() function
In the following example, the addNumbers
function is converted into a static method of the Mathematics
class using the staticmethod()
function. This allows the function to be called directly on the class without creating an instance.
class Mathematics:
def addNumbers(x, y):
return x + y
# create addNumbers static method
Mathematics.addNumbers = staticmethod(Mathematics.addNumbers)
print('The sum is:', Mathematics.addNumbers(5, 10))
output
The sum is: 15
Example 2: Using @staticmethod Decorator
A more pythonic way to define static methods is using the @staticmethod
decorator.
class Mathematics:
# create addNumbers static method
@staticmethod
def addNumbers(x, y):
return x + y
print('The sum is:', Mathematics.addNumbers(5, 10))
output
The sum is: 15
Example 3: Create a utility function as a static method
Static methods are primarily used for utility functions that do not depend on the state of the class or its instances.
Static methods have a limited use case because, like class methods or any other methods within a class, they can not access the properties of the class itself.
However, when you need a utility function that does not access any properties of a class but makes sense that it belongs to the class, we use static functions.
Static methods can be called both on the class itself and on an instance of the class, but the instance is ignored except for its class.
For example, create a Dates
class and in order to convert the slash-dates to dash-dates, let's create a utility function toDateWithDash
in Dates
class.
class Dates:
def __init__(self, date):
self.date = date
def getDate(self):
return self.date
@staticmethod
def toDateWithDash(date):
return date.replace("/", "-")
date = Dates("25-02-2024")
other_date = "25/02/2024"
dateWithDash = Dates.toDateWithDash(other_date)
if(date.getDate() == dateWithDash):
print("Equal")
else:
print("Unequal")
output
Equal
Example 4: How inheritance works with static method?
Static methods are used when there is a need to prevent subclasses from changing or overriding a specific method's implementation.
class Dates:
def __init__(self, date):
self.date = date
def getDate(self):
return self.date
@staticmethod
def toDateWithDash(date):
return date.replace("/", "-")
class DatesWithSlashes(Dates):
def getDate(self):
return Dates.toDateWithDash(self.date)
date = Dates("25-02-2024")
other_date = DatesWithSlashes("25/02/2024")
if(date.getDate() == other_date.getDate()):
print("Equal")
else:
print("Unequal")
output
Equal
What is a Static Method?
Static methods in Python are similar to class methods in that they are bound to a class rather than instances of that class. They do not require an instance of the class to be called, making them independent of the object's state.
The key point between static methods and class methods is in their relationship with the class:
- A static method operates only on the parameters it receives and is unaware of the class it belongs to. It does not have access to the class or its instances.
- A class method, on the other hand, is aware of the class, as it takes the class itself as its first parameter. This allows it to interact with the class state or create new instances of the class.
Both static methods and class methods can be invoked on the class itself or on instances of the class, but their behavior and capabilities differ significantly. Static methods are typically used for utility functions that do not depend on the class or instance state, while class methods are often used for factory methods that create instances of the class or its subclasses.
They can be called both by the class and its object.
Class.staticmethodFunc()
# or even
Class().staticmethodFunc()