Dremendo Tag Line

Static Methods in Python Programming

OOPs in Python

In this lesson, we will understand what is Static Method in Python Programming and how to create them along with some examples.

What are Static Methods in Python?

Static Methods are written in a class using the @staticmethod decorators above them. These methods are bound to the class and not to the object, which means that these methods can be called using the class name, and calling the methods using the object name is not necessary. However, the object of the class can also access the static methods using the object name.

Static Methods are used to create a utility class, also known as the helper class, that contains only static methods and can be reused across the programs. It's not required to create an object of a utility class to access its static method because we can also assess the static methods using its class name.

For example, all the methods declared in math class are static. So whenever we need to call any static method of math class, we access it by calling the class name with a dot (.) operator and then writing the name of the static method like math.pow().

video-poster

Example

class Record:

    # Creating a static method for addition
    @staticmethod
    def add(a,b):
        return a+b

    # Creating a static method for substraction
    @staticmethod
    def substract(a,b):
        return a-b

    # Creating a static method for multiplication
    @staticmethod
    def multiply(a,b):
        return a*b

    # Creating a static method for division
    @staticmethod
    def divide(a,b):
        return a/b


print('Enter 2 numbers')
x=int(input())
y=int(input())

# Call all the static methods of the class Record one by one
print('Addition = %d' %(Record.add(x, y)))
print('Substraction = %d' %(Record.substract(x,y)))
print('Multiplication = %d' %(Record.multiply(x,y)))
print('Division = %d' %(Record.divide(x,y)))

Output

Enter 2 numbers
10
5
Addition = 15
Substraction = 5
Multiplication = 50
Division = 2

Note: In any of the above declared static methods, we have not used self as the first parameter because static methods work at the class level, and they don't need to know anything about the object or its memory address. They only work with the provided parameters.