Python static method Explained [Practical Examples]

 

Introduction to Python static method

In Python, a method is a function that is available for a given object because of the object's type. There are different types of methods based on their declaration and usage, for example, class method and static method.

In this article, we will learn about the python static method. We will cover two different ways to declare the python static method and will see how we can call the static method. At the same time, we will also discuss how the python static method is different from the Python class method through examples. Also, we will cover how we call a static method with arguments and how to use arithmetic operations in a python static method. Moreover, we will discuss why and when we use the python static method.

Advertisement

In a nutshell, this tutorial will contain all the necessary information and examples that you need to know in order to start working with the python static method.

 

Getting started with Python static method

Python static method is extremely similar to the python class-level method, the difference is that a static method is bound to a class rather than the objects for that class. This means that a static method can be called without an object for that class and cannot modify the state of an object as they are not bound to it.

In this section, we will see how we can declare the python static method and call it in our python program.

 

Method-1 Declaring Python static method

The simplest way of declaring the python static method is to use staticmethod() which takes a method as a parameter and returns that method as a static method. The simple syntax looks like this.

staticemethod(function_name)

This method takes the function as a parameter. Let us now take an example and see how we can use staticmethod() to create a new python static method. See the example below.

# python class
class Sum: 
  # python method   
  def sum(num1, num2):
    #   return the sum of numbers
    return num1 + num2
# convert sum() to python static method
Sum.sum = staticmethod(Sum.sum)
# calling the static function
sum = Sum.sum(5, 7)
# printing the return value
print('Sum:', sum)

Output:

Advertisement
Sum: 12

In the above example, the staticemethod() converts the sum() method into python static method.

 

Method-2 Declaring Python static method

The staticmethod() is considered an un-Pythonic way of creating a static function. Hence, in newer versions of Python, we can use the @staticmethod decorator. The simple syntax looks like this:

@staticmethod
def functionName():
    # function statements

A decorator in Python is a function that takes another function as its argument and returns yet another function. Here we had used the staticmethod() as a decorator which returns the function as a python static method. Now let us take an example and see how we can use the decorator for the python statice method. See the example below:

# python class
class Sum:
  # python decorator
  @staticmethod 
  # python method   
  def sum(num1, num2):
    #   return the sum of numbers
    return num1 + num2
# calling the static function
sum = Sum.sum(5, 7)
# printing the return value
print('Sum:', sum)

Output:

Sum: 12

In the above example, @staticmethod is a python decorator which converts the given method into a static method.

 

Python static method inside the class

A class can contain both static and non-static methods. If we want to call non-static methods, then we have to create an object but we can call the python static method without creating an object. For example see the python program below:

# python class
class Methods:
    # static method decorator
    @staticmethod
    # python static method
    def static_method():
        print("This is static method")
    # python non static method
    def nonstatic_method(self):
        print("This is not a static method")
Methods.static_method()

Output:

This is static method

Notice that we did not create a new object to call the method. If we will try to call the non-static method in the same way, it will give us an error. See the example below:

Advertisement
# python class
class Methods:
    # static method decorator
    @staticmethod
    # python static method
    def static_method():
        print("This is static method")
    # python non static method
    def nonstatic_method(self):
        print("This is not a static method")
# calling non static method
Methods.nonstatic_method()

Output:

Python static method

Notice that we get an error, it is because we did not have to create an object and we tried to call the class method. First, we need to create an object to call its non-static methods.

 

Difference between Python static method and class method

A class method is a method that is bound to the class and not the object of the class. They have the access to the state of the class as it takes a class parameter that points to the class and not the object instance. In this section, we will see some of the differences between the python static method and the class method. See the list below:

  • A class method takes cls as the first parameter while a static method needs no specific parameters.
  • A class method can access or modify the class state while a static method can not access or modify it.
  • Static methods know nothing about the class state. They are utility-type methods that take some parameters and work upon those parameters. On the other hand class methods have class as a parameter.
  • We use the @classmethod decorator in python to create a class method and we use the @staticmethod decorator to create a static method in python.

 

When we use Python static method?

Grouping utility functions to a class: Static methods have a limited use case because, like class methods or any other methods within a class, they cannot access the properties of the class itself. However, when we need a utility function that doesn't access any properties of a class but makes sense that it belongs to the class, we use static functions.

Having a single implementation: Static methods are used when we don't want subclasses of a class change/override a specific implementation of a method. It performs the specific task at the time and remains constant throughout the program.

Now let us take of python static method which only performs specific tasks. We will create a utility function that will only replace slash dates to dash dates. See the example below:

# python class
class DashDates:
    # constructor
    def __init__(self, date):
        self.date = date
    # python class method
    def getDate(self):
        return self.date
    # python static method
    @staticmethod
    def toDash(date):
        # replaces slashes with dash
        return date.replace("/", "-")
# creating new date with slashes
OldFormat = "15/12/2016"
# converting slashes dates to dashdates
dateWithDash = DashDates.toDash(OldFormat)
# printing the new date
print(dateWithDash)

Output:

15-12-2016

Notice that the static method in the above python program just replaces the slashes with dashes and returns a new formatted date.

Advertisement

 

Python static method with arguments

In Python, we do not have to use self or cls attributes to create a static method. Like a normal function, we can create it and add the arguments as per requirements. There is no need to use self with arguments as we used in class methods. Let us take an example of the python static method with arguments. We will create a static method that can take arguments. See the example below;

# python class
class Person:
    # python constuctor
    def name(self, name):
        self.name = name
    # python class method
    def Name(self, name):
        print("My name is {}".format(name))
    # python static method
    @staticmethod
    def about(age, city):
        # printing the arguments
        print("My age is {}".format(age))
        print("I am from {}".format(city))
# creating new object
man = Person()
# calling the class method
man.Name('Bashir')
# calling the static method
Person.about(22, 'Gilgit')

Output:

My name is Bashir
My age is 22
I am from Gilgit

Notice that in the class method, we had used the self keyword which refers to the object while in the python static method, we did not use the keyword self, because it is not needed in static methods.

 

Arithmetic operations using Python static method

In Python, there are different operators that perform various functions. You can read more about python operators from the article on Python operators. Arithmetic operators are one of those pythons operators that are used to perform mathematical operations. In this section, we will see how we can use the python static method for arithmetic operations using arithmetic operators. See the example below:

# python class
class Arithmetic_operations:
    # python static method for adding numbers
    @staticmethod
    def addition(num1, num2):
        # printing the sum of number
        print("The sum is: {}".format(num1 + num2))
    # python static method for multipication of numbers
    @staticmethod
    def multipication(num1, num2):
        # printing the producto of two numbers
        print("The product is: {}".format(num1*num2))
    @staticmethod
    def subtraction(num1, num2):
        # printing the subtraction
        print("The subtraction is: {}".format(num1-num2))
# calling the static methods
Arithmetic_operations.addition(10, 5)
Arithmetic_operations.multipication(10, 5)
Arithmetic_operations.subtraction(10, 5)

Output:

The sum is: 15
The product is: 50
The subtraction is: 5

Notice that we have created a different static method for each of the operations in the above program.

 

Summary

A static method is also a method that is bound to the class and not the object of the class. A static method can't access or modify the class state. In this tutorial, we learned about Python static method. We learned two different ways to declare a static method inside our Python class. We also discussed some of the differences between the python static method and the python class method and also covered when to use a static method inside our Python class.

At the same time, we also learned how to create a static method with multiple arguments and perform arithmetic operations. To summarize, this tutorial contains all the necessary information and examples that you need to know in order to start working with python static methods.

 

Further Reading

Python built-in methods
Python static method documentation
Python class

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment