How to use Python staticmethod()
Static methods can be called directly using the class name without requiring an instance of the class. This feature of Python’s staticmethod
enables a clear distinction between class logic and instance data.
What is Python’s staticmethod
used for?
Python staticmethod
is both a function and a decorator. It is used to designate methods that operate independently of class instances. Decorators in Python are functions that modify the behavior of other methods by adding supplementary functionality before or after their execution, without altering the original function code. Unlike instance methods, static functions don’t require an implicit parameter such as self
.
The use of staticmethod
in Python offers a focused approach to structuring functions within classes that don’t require access to instance data. Since they aren’t bound to an instance, they cannot modify the state of an object. Within classes, they serve as valuable tools for executing common tasks or offering global functionality. For example, they can house utility programs, conversion routines and general helper functions that can be invoked without instance data.
- 99.9% uptime
- PHP 8.3 with JIT compiler
- SSL, DDoS protection, and backups
What is the syntax of Python’s staticmethod
?
There are two ways to create static methods in Python. You can use the staticmethod()
function or the @staticmethod
decorator.
staticmethod()
staticmethod()
is a built-in Python function that makes a method of a class static. The return value of Python staticmethod()
is a static method for the function that is passed as an argument. The syntax is:
class Class:
def staticmethodFunc(x,y):
return x + y
Class.staticmethodFunc = staticmethod(Class.staticmethodFunc)
print('Sum = ', Class.staticmethodFunc(5,7)) # Output: Sum = 12
pythonBy passing the staticmethodFunc()
function defined in the Class
class as an argument to staticmethod()
, we can now call the custom method directly via the class name.
@staticmethod
The @staticmethod
decorator is a shorter and more common method to mark a function as static. The decorator is placed above the method in the class definition. The syntax is:
class Class:
@staticmethod
def staticmethodFunc(x, y):
return x + y
print('Sum = ', Class.staticmethodFunc(5,7)) # Output: Sum = 12
pythonThe @staticmethod
decorator signals to the interpreter that the defined function should be treated as a static method.
Python staticmethod
code examples
You can use static methods for a variety of tasks. Below are a few practical examples of how to use static methods.
Converting units
Python staticmethod
is very useful for converting units.
class Converter:
@staticmethod
def hoursToMinutes(hours):
return hours * 60
@staticmethod
def minutesToHours(minutes):
return minutes / 60
hours = 3
converted_minutes = Converter.hoursToMinutes(hours)
print(f"{hours} hours are {converted_minutes} minutes.") # Output: 3 hours are 180 minutes.
minutes = 180
converted_hours = Converter.minutesToHours(minutes)
print(f"{minutes} minutes are {converted_hours} hours.") # Output: 180 minutes are 3 hours.
pythonIn this example, the class Converter
has two static methods to convert between hours and minutes. The method hoursToMinutes()
converts hours into minutes, while minutesToHours()
converts minutes into hours.
We can call the static methods via the class name without having to create an instance of the class. They are accessed via Converter.hoursToMinutes()
or Converter.minutesToHours()
, where Converter
is the class name. We output the result in an f-string, a Python string format that links expressions.
Auxiliary functions for math calculations
You can also use Python’s staticmethod()
to define auxiliary functions for secondary calculations.
class Calculator:
@staticmethod
def square(x):
return x * x
@staticmethod
def sqroot(x):
return x ** 0.5
num = 9
square = Calculator.square(num)
print(f"The square of {num} is {square}.") # Output: The square of 9 is 81.
root = Calculator.sqroot(num)
print(f"The square root of {num} is {root}.") # Output: The square root of 9 is 3.
pythonThe code example demonstrates the Calculator
class with static methods for calculating the square and square root of a number. We use the @staticmethod
decorator to mark square()
and sqroot()
as static methods. Without creating an instance of the class, we call the methods via the class name. We concatenate the results of Calculator.square()
and Calculator.sqroot()
in an f-string.
Validation of entries
Another use of Python’s staticmethod is the validation of inputs.
class Validator:
@staticmethod
def isInteger(num):
try:
int(num)
return True
except ValueError:
return False
@staticmethod
def isDecimal(num):
try:
float(num)
return True
except ValueError:
return False
input = "123"
is_integer = Validator.isInteger(input)
print(f"Is '{input}' an integer? {is_integer}") # Output: Is '123' an integer? True
input = "3.14"
is_dec = Validator.isDecimal(input)
print(f"Is '{input}' a decimal number? {is_dec}") # Output: Is '3.14' a decimal number? True
pythonThe Validator
class comprises the two static methods: isInteger()
and isDecimal()
. These functions check whether a given input is an integer or a decimal number. The Python staticmethod isInteger()
takes an input and tries to convert it into an integer (int(num))
. If successful, True
is returned. Otherwise, we get False
if a ValueError
exception is caught, which happens when validation isn’t possible.
We use the isDecimal()
method to convert the input into a decimal number (float(num))
. If successful, True
is returned, otherwise False
. We then use the isInteger()
and isDecimal()
static methods of the Validator
class to check the inputs "123"
and "3.14"
. The results are true for both functions.
Manipulation of strings
In the example below, we define the class StringManipulation
with the static method reverseText()
. This takes a text as a parameter and uses the slicing syntax [::-1]
to reverse the text "Hello World!"
and return the result.
class StringManipulation:
@staticmethod
def reverseText(text):
return text[::-1]
input_text = "Hello World!"
result = StringManipulation.reverseText(input_text)
print(f"Reversed text of '{input_text}': {result}") # Output: Reversed text of 'Hello World!': !dlroW olleH
python