Updated April 14, 2023
Introduction to Static Method in Python
The following article provides an outline on Static Method in Python. A static method is a method which is bound to the class and not to the objects of that class. But static method can’t access or modify the state of a class unlike a class method. Static method is defined inside the Class but it should not be considered as a class method. A class method takes “cls” as its first parameter while a static method needs no specific parameters. A class method can access and modify class state whereas a static method can’t access or modify it. Static method knows nothing about class state. A class method is created using @classmethod decorator while static method is created using @staticmethod decorator.
In python static methods can be defined in two ways:
1. Using staticmethod()
2. By using @staticmethod decorator
class class_name: @staticmethod def static_method_name(): // code to be executed
Approach (2) is the most common way in python to create static methods.
Examples of Static Method in Python
Given below are the examples:
Program for basic calculator.
Basic calculator using Class and static method.
@staticmethod decorator is used while defining static methods.
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))
- 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 is used to identify that the following defined methods are static ones.
- User is then prompted to enter values for two variables which are then passed when static methods are called. Static methods are called as class_name.static_method().
Output for all the methods is then printed in respective print statements as shown in below output.
This program can be implemented using staticmethod().
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))
Program to format date.
# 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))
Program to categories human and checking eligibility to vote.
# Program to categories a human age and check his eligibility to vote class Classifier: # method to classify a person's age @staticmethod def ageClassfier(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 adult" # method to check voting eligibility @staticmethod def eligibility(age): if age > 18 : return "Eligible to vote" else : return "Not eligible to vote" # Prompting user to enter his age print("Enter age") inp_age = int(input()) print("You are a/an", Classifier.ageClassfier(inp_age),'and you are',Classifier.eligibility(inp_age))
- 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. Second method is eligibility() which will determine whether this person is eligible to vote or not.
- User is then prompted to enter his age.
- Results (person age category and his eligibility) are then printed.
Program to print number pattern ( up to digit 10).
# 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()
Though there are class and instance method to accomplish object oriented paradigm. Static methods have a different use case. When we need to implement some functionality not w.r.t class or an object, we create static method. This is useful to create utility methods as they are not tied to an object lifecycle.
We hope that this EDUCBA information on “Static Method in Python” was beneficial to you. You can view EDUCBA’s recommended articles for more information.