Python Static Method – Explained with Examples

Python Static Method – Explained with Examples. Python is most often the favourite language for developers for programming. With many useful it makes code easier to read, maintain, and faster to run.

Using static methods is an important part of object oriented programming to organize and make code easier to understand.

The article explains Python’s static methods in detail and demonstrates how to utilize them. This article is for  both new and experienced Python developers who want to make their code run faster and more efficiently.

What is a Python Static Method?

Static methods in Python are bound to the class itself, not to a specific instance or class object. So they cannot access or modify the state of the object.

Python also does not pass the self parameter to static methods by default, so they cannot change the class state either. You do not need to have the class object to call the static methods.

So, static methods are often used for creating utility functions that are responsible for very specific or commonly needed tasks.

Basically, a method is declared static when you need some functionality that applies to the entire class rather than just an object. Since utility methods are typically unrelated to object lifecycles, this is quite helpful when you need to create them.

Advantages of a Static Method

  • Improve the clarity and readability of the overall code.
  • Reusability: static methods are independent of class instances, so they are reused all across your codebase without the need to make new objects.
  • Encapsulation: they encapsulate functionality that does not concern the class or its instances.
  • Less memory consumption and improved performance: static methods have only one copy per class as opposed to instance methods, which have a copy for every object. This leads to improved memory consumption and execution.
  • Consistency: the reusability and uniform performance of the static methods bring consistency to the code.

Python static methods vs class methods

Static methods and class methods are inherently different because the class method requires the class self object as the first argument, while the static methods do not need specific arguments.

This means that static methods often don’t have any knowledge about the class state. These are utility methods that operate on certain parameters after receiving them. However, the class methods need class objects as a parameter.

It means that the class method accesses or modifies the class state, while the static method has nothing to do with it.

Class methods are usually for creating factory methods, such as constructors, while static methods are for making utility functions.

Follow this post to learn about Python static methods and their various examples.

Python Static Method - Explained with Examples

How to Define Python Static Method - Explained with Examples

The methods in a Python class become instance methods by default on invocation. So, you need to declare your static methods clearly.

There are 2 approaches to declaring your static methods. One is to use the static method annotation before the method definition. The other one is to declare your method as a static method using the staticmethod() function after the function definition. 

Using @staticmethod Decorator

Using the @staticmethod decorator for the static method is more convenient, as you do not need to repeat the statement definition everywhere you use the static method.

Consider the following example of an addition function within the calculator class:

				
					class Calculator:

    # create addNumbers static method
    @staticmethod
    def addition(x, y):
        return x + y

print('Result:', Calculator.addition(15, 10)) #output: 25

				
			

You have declared the addition function as a static function by using the @staticmethod before its definition.

The static function is called directly through the class name, and no class object is used here. Because the static functions have nothing to do with objects or class instances.

Now, consider the following code to understand the difference between the instance and static methods:

				
					class MyClass:
    def __init__(self, value):
        self.value = value
 
    def get_value(self):
        return self.value
        
    @staticmethod
    def addNumbers(x, y):
        return x + y
 
# Create an instance of MyClass
obj = MyClass(10)
 
# Call the get_value instance method
print(obj.get_value())  # Output: 10

# Using the class name to call static method
print(MyClass.addNumbers(20, 30))  # Output: 50

				
			

See that the instance method name get_value needs the class self object as an argument for its calling. At the same time, the static method does not need such a self-object as an argument.

Using staticmethod() Function

Also use the staticmethod() function to convert any defined function into a static function. This method is somewhat obsolete and only recommended when there is support for older versions of Python, for example, Python 2.2 or 2.3.

The basic syntax of this function is as follows:

				
					staticmethod(function)
				
			

Where the function is the method name you wish to convert to a static method, this function returns the static method.

Consider the following example:

				
					class Employee:
    def sample(x):
        print('Inside static method', x)

# convert to static method
Employee.sample = staticmethod(Employee.sample)
# call static method
Employee.sample(10)  #output: Inside static method 10

				
			

Here, the method sample definition is just like any other function. But later, its method name is passed as an argument to the staticmethod() function, and the method is converted to a static function.

This method is quite convenient if you want to declare any method as static after its definition or if you need to call a function from the class but want to avoid transforming a function into an instance method. 

How to Call Python Static Method - Explained with Examples

As mentioned earlier, the static methods cannot access or change class state, so their invocation is possible from nearly anywhere.

There are two aspects we need to discuss when it comes to calling a static method. One is syntax, and the other is the invocation place. The following sections discusses each case separately.

Using the Class Name

The static method is bound to the class, so it does not specifically need the object reference in its invocation.

See in the following example that the static method is using the class name Employee for its invocation.

				
					class Employee:
    @staticmethod
    def sample(x):
        print('Inside static method', x)

# call static method
Employee.sample(10)

				
			

Using the Class Object

If you are already working with the object, you do not need to go back specifically to the class name; use the object while calling a static method. It will not affect the static method status or change the class state.

See the following example:

				
					class Employee:
    @staticmethod
    def sample(x):
        print('Inside static method', x)
        
#Making a class object        
emp=Employee()
 
# call static method using class object
emp.sample(10)
				
			

See the static method named sample is called out using the class object emp. But the result does not throw an error, and the result is the same.

From the Class Method

Consider the following example to see how the class method calls the static method.

				
					class Test :
    @staticmethod
    def static_method():
        print('static method')

    @classmethod
    def class_method(cls) :
        cls.static_method()

# call class method
Test.class_method()
				
			

See how the class method invokes the static method. The static method returns the print statement as a result.

From the Instance Method

Similarly, call the static method from inside the instance method. See the following code, for example.

				
					class Test :
    @staticmethod
    def static_method():
        print('static method')
    
    def instance_method(cls) :
        cls.static_method()
        
test=Test()     # making a class object   

# call class method
Test.instance_method(test)
				
			

You can see that the static method is called in the instance method. This example also highlights the difference between static methods and instance methods, as the instance method would throw an error if you called it without the class object or instance.

From Another Static Method

Call your static method from another static method easily. Consider the following code:

				
					class Test :
    @staticmethod
    def static_method_1():
        print('static method 1')

    @staticmethod
    def static_method_2() :
        Test.static_method_1() #call static method 1

# call static method 2
Test.static_method_2()
				
			

The test class has 2 static methods, namely static_method_1 and static_method_2, where static_method_2 calls upon static_method_1. The class name invokes the static method as usual.

Python Static Method - Explained with Examples Conclusion

In general, static methods are very important in Python programming because they help make code clear, reusable, encapsulated, faster, easier to test, and consistent.

Adding static functions to your code makes your Python apps easier to manage and run faster.

This article explores the Python static method in detail, including its differences from other method types, its advantages, and its use.

Explore our Python section to learn more.

Avatar for Sobia Arshad
Sobia Arshad

Information Security professional with 4+ years of experience. I am interested in learning about new technologies and loves working with all kinds of infrastructures.

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x