How to use static methods in Python

Static method

A static method in Python is a method that belongs to the class rather than an instance of the class. This means that you can call a static method on the class itself, without having to create an instance of the class.

Static methods are defined using the ‘@staticmethod‘ decorator and do not have access to the instance of the class (‘self‘). This makes them ideal for utility functions that don’t depend on any instance-specific state. For example, you could use a static method to perform a calculation or format a string that’s independent of any particular instance of the class.

Static methods are called using the class name, rather than an instance of the class. Here’s an example:

Python
class ExampleClass:
    @staticmethod
    def static_method(arg1, arg2):
        # code here
        pass

You can call the static method using the class name, like this:

Python
ExampleClass.static_method(arg1, arg2)

Static methods can be useful for grouping related functionality together, and for providing a convenient way to call utility functions that don’t depend on any instance-specific state. However, they are not meant to be used for methods that depend on the state of a particular instance of the class, as they do not have access to ‘self‘. For those, you should use regular instance methods.

Format String with Static Method

To format a string using a static method, you can use the ‘str.format()‘ method and provide the values as arguments to the method. Here’s an example:

Python
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    @staticmethod
    def get_greeting():
        return "Hello, {}! You are {} years old."
    
    def greet(self):
        return self.get_greeting().format(self.name, self.age)

# Create a Person object
person = Person("Alice", 25)

# Call the greet() method to print the greeting
print(person.greet())

In this example, we define a class ‘Person‘ that has a static method ‘get_greeting()‘ that returns a string template with two placeholders for the name and age of a person. The ‘greet()‘ method of the class calls the ‘get_greeting()‘ method and uses the ‘str.format()‘ method to fill in the placeholders with the actual name and age of the person.

We then create a ‘Person‘ object ‘person‘ with the name “Alice” and age 25, and call the ‘greet()‘ method to print the greeting for that person.

The output of this code will be:

Hello, Alice! You are 25 years old.

As you can see, the ‘greet()‘ method formats the string template returned by the ‘get_greeting()‘ method with the actual name and age of the person, using the ‘str.format()‘ method.

Perform Calculation with Static Method

To perform calculations with a static method in Python, you can define a method inside a class and use the ‘@staticmethod‘ decorator to mark the method as a static method. Here’s an example:

Python
class Calculator:
    @staticmethod
    def add(x, y):
        return x + y
    
    @staticmethod
    def subtract(x, y):
        return x - y
    
    @staticmethod
    def multiply(x, y):
        return x * y
    
    @staticmethod
    def divide(x, y):
        if y == 0:
            raise ValueError("Cannot divide by zero")
        return x / y

# Use the static methods of the Calculator class
result1 = Calculator.add(5, 3)
result2 = Calculator.subtract(10, 2)
result3 = Calculator.multiply(4, 6)
result4 = Calculator.divide(12, 3)

# Print the results
print("Result1:", result1)
print("Result2:", result2)
print("Result3:", result3)
print("Result4:", result4)

In this example, we define a class ‘Calculator‘ that has four static methods for performing basic arithmetic operations: add(), subtract(), multiply(), and divide(). Each method takes two arguments ‘x‘ and ‘y‘ and returns the result of the corresponding operation.

We then use the static methods of the ‘Calculator‘ class to perform some calculations and store the results in variables ‘result1‘, ‘result2‘,’ result3', and ‘result4‘. Finally, we print the results using the ‘print()‘ function.

The output of this code will be:

Result1: 8
Result2: 8
Result3: 24
Result4: 4.0

As you can see, the static methods of the ‘Calculator‘ class perform the specified arithmetic operations and return the results, which we can store in variables and use as needed.

Share The Tutorial With Your Friends
Twiter
Facebook
LinkedIn
Email
WhatsApp
Skype
Reddit

Check Our Ebook for This Online Course

Advanced topics are covered in this ebook with many practical examples.