Introduction to Python @staticmethod
The following article provides an outline for Python @staticmethod. A static method binds to the class it represents rather than being bound to any object of any class. It is a method with no right to access or modify class state. The @staticmethod is a built-in function and returns a static method. These static methods resemble other class methods and are associated with a class. These staticmethod do not require class instance creation, which is why they are not dependent on the state of an object. People typically use these static methods to process class-related data rather than instance-specific data.
Table of Contents
Syntax
There are two ways to define static methods in Python:
1. Using @staticmethod decorator
The standard syntax for @staticmethod decorator is as follows:
@staticmethod(function)
The syntax uses the keyword “staticmethod,” and the method necessitates a function for proper execution. It doesn’t have to be necessarily invoked using a function; we can implement the @staticmethod without a function.
The parameter we pass here is a function that we intend to convert into a static method by passing the function as a parameter. And for the return value, the staticmethod returns a static method of the function that we passed.
2. Using staticmethod()
Staticmethod(class_name.method())
How does @staticmethod Decorator work in Python?
- The @staticmethod is a Python Descriptor. When called, Python will invoke the __get__ method when you have to access the object. This is where the translation begins in Python.
- This staticmethod is also similar to @classmethod. When we initiate the staticmethod in our code, it passes the power to the function that we have passed, and execution turns to the function.
- One of the major applications of using staticmethod is to create multiple utility functions.
Examples of Python @staticmethod
Below are the different examples as follows:
Example #1
For our first example, we will call for a print statement, including the @staticmethod. Here, we will not pass any function for the decorator.
Code:
class State:
@staticmethod
def city():
print("Pune - Simple Example to Demonstrate working of @staticmethod, without function.")
s=State()
s.city()
Explanation:
Started with creating a class named State and called the @staticmethod decorator within the first class. Then we have a simple function defined named city, and within this function is our simple print statement, which will print a simple message on successful execution.
Then, we assigned our first class with a simple variable as s. In the end, we have s.city(), which means we call for the city() function, which is part of the state class. The s.city() can be understood as calling the city function a part of s, where s is the state class.
Output:
Example #2
We will implement the @staticmethod constructor along with the function. So here, we will pass a function and check the output.
Code:
class Sample:
def Ex():
print("This is an example for @staticmethod with function")
Ex = staticmethod(Ex)
Sample.Ex()
Explanation:
Similar to our first example, we have a simple class and a function defined within the class. We aim to get the print statement as output through @staticmethod. We then have another variable to call the staticmethod, and we have passed the function we created. Finally, we have called the function Sample.Ex(), meaning call for Sample class, which holds the Ex() function. The function is expected to hold the value that produces the output.
Output:
As expected, the output is “This is an example for @staticmethod with function,” which was our intention. Here, we saw how a staticmethod works when passed with a function. Earlier, we saw the working of staticmethod without passing any function.
Example #3
We will pass an age that will be checked and defined if the person is an adult. The code for the program of age and adult function is as follows.
Code:
from datetime import date
class Ex_Per:
def __init__(self, age):
self.age = age
@staticmethod
def isAdult(age):
return age > 18
n_age=33
sample = Ex_Per(n_age)
print (sample.age)
print (Ex_Per.isAdult(n_age))
Explanation:
Our main aim here is to print the person’s age and the result in the Adult function. We started with importing date from the datatime module. Then, we have our class Ex_Per, which has the definition of age. Then we have our @staticmethod, which has our function as an adult, and our function is responsible for checking if the given age is greater than 18 or not. They then declared a simple variable to hold the age, which is 33 for this example.
Then, we have another variable to hold our class and age. Finally, with our first print statement, we print the age of the person as a sample.age. This sample.age can be read as a sample that holds the class Ex_Per and, within that, the age function. In our second print statement, we have Ex_Per.isAdult(n_age). Our last line will simple print either true or false based on the result of the Adult function. The a_age here is the variable that holds our age, which is 33.
Output:
As you can see, we tried the same example with two different ages. When we executed the code with age as 11, it printed False for being an adult. 11 is smaller than 18, so the person with the age of 11 is not an adult. Then we again executed the code with age as 33, and as 33 is bigger than 18, the result for Adult is True. This program was an example of the implementation of @staticmethod.
Example #4
Create a basic calculator using classes and static methods. Use the @staticmethod decorator when defining static methods.
Code:
class Calculator:
@staticmethod
def add(a,b):
return (a+b)
@staticmethod
def sub(a,b):
return(a-b)
@staticmethod
def mul(a,b):
return (a*b)
@staticmethod
def div(a,b):
return(a/b)
# Prompting user to enter two values
print("Please enter values for x and y")
x = int(input())
y = int(input())
# static method are called using class_name.method()
print("Sum of two numbers entered" , Calculator.add(x, y) )
print("Difference of two numbers entered", Calculator.sub(x, y))
print("Multiplication of two numbers entered", Calculator.mul(x, y))
print("Division of two numbers entered",
Calculator.div(x, y))
Explanation:
- A class “Calculator” is created. Inside this, four static methods add(), sub(), mul(), and div() and are defined to perform four basic arithmetic operations.
- @staticmethod decorator identifies that the following defined methods are static ones.
- Prompt the user to enter values for two variables and then pass these values when calling the static methods using the format: class_name.static_method().
Output:
Output for all the methods is then printed in respective print statements, as shown in the below output.
This program can be implemented using staticmethod().
Code:
class Calculator:
# no self parameter or cls paramter is used as these are for instance and class methods
def add(a, b):
return (a + b)
def sub(a, b):
return (a-b)
def mul(a, b):
return (a * b)
def div(a, b):
return (a / b)
print("Enter values for x and y")
x = int(input())
y = int(input())
# create add static method
Calculator.add = staticmethod(Calculator.add)
print('The sum is:', Calculator.add(x, y))
# create sub static method
Calculator.sub = staticmethod(Calculator.sub)
print('The difference is:', Calculator.sub(x, y))
# create mul static method
Calculator.mul = staticmethod(Calculator.mul)
print('The multiplication is:', Calculator.mul(x, y))
# create div static method
Calculator.div = staticmethod(Calculator.div)
print('The division is:', Calculator.div(x, y))
Output:
Example #5
Program to format date.
Code:
# Program to format date
class Format:
# declaring static method to format input date
@staticmethod
def date_format(indate):
format_date = indate.replace('/','-')
return format_date
inp_date = '2019/12/19'
print("Formatted date :", Format.date_format(inp_date))
Output:
Example #6
Program to categorize humans and check eligibility to vote.
Code:
class Classifier:
@staticmethod
def ageClassifier(age):
if age > 0 and age <= 12: return "Child" elif age > 12 and age <= 18: return 'Adolescence' elif age > 18 and age <= 59: return 'Adult' else: return "Senior Citizen" @staticmethod def checkVotingEligibility(age): if age >= 18:
return "Eligible to vote"
else:
return "Not eligible to vote"
# Prompting the user to enter their age
try:
age = int(input("Enter your age: "))
if age < 0:
print("Please enter a valid age.")
else:
age_category = Classifier.ageClassifier(age)
eligibility = Classifier.checkVotingEligibility(age)
print(f"You are in the '{age_category}' category. You are {eligibility}.")
except ValueError:
print("Please enter a valid age as a number.")
Output:
Explanation:
- Class Classifier is created.
- Two static methods are defined. First is ageClassfier(), which will classify a person’s age and categories into one of the four categories. The second method is eligibility(), which will determine whether this person is eligible to vote or not.
- Prompt the user to enter their age.
- Results (person age category and eligibility) are then printed.
Example #7
Program to print number pattern ( up to digit 10).
Code:
# Program to print a number pattern
class Pattern:
@staticmethod
def pattern():
for num in range(10):
for i in range(num):
print(num, end=" ") # print number
# new line after each row to display pattern correctly
print("\n")
Pattern.pattern()
Output:
Conclusion
The @staticmethod decorator is essentially another built-in function that doesn’t require any parameters. You use it to define static methods, which do not take any parameters and cannot access or modify the class’s state. Developers employ @staticmethod primarily when creating utility functions. Static methods are unaware of any internal class operations or changes.
Recommended Articles
We hope that this EDUCBA information on “Python @staticmethod” was beneficial to you. You can view EDUCBA’s recommended articles for more information.