Static Methods in Python

· 2 min read March 18, 2022

banner

What is a Static method in Python ?

This post assumes that you have basic knowledge about object-oriented programming in python and specifically classes

Static Methods are class-level methods. This means that they are independent of the object instance lifecycle.

Describing it a little more by class level I mean that the static methods are not bound to the objects initialized from the class. and they are initialized once and can be called directly from the class.

If this is a lot to digest at the start. This may be the case if you are new to OOP. Don’t worry we are going to dive deep into it in this blog post.

How to create a static method .

Static methods are created by using the static method decorator. As the static method is independent of the object and cant manipulate the state of the object instance. It doesn’t take object-instance(self) as its argument.

so, let’s jump into a code snippet to see it in action

#lets create a class to represent humans

class Human:
    @staticmethod
    def species():
        #we are creating a static method to return the species of humans
        # note that we are not taking self as the argument
        return "Homo Sapiens"

boy = Human()
# we have created object boy from Human class
print(boy.species())
# prints Homo Sapiens

# as static methods are independent of the object we can also call them directly on the class
print(Human.species())
# prints Homo Sapiens

Why do we need static methods ?

Are you a little confused, why do we even need them when everything that a static method does can be done directly from a regular method.

if you are thinking like it, You are partly correct and partly wrong.

You are right everything that a static method can do a regular can also be done using a regular method but there is a big caveat. which I tried to explain at the start of the post.

and that’s regular methods are bound to every instance of the class. This means it takes extra memory and also affects the performance of the code.

while static methods are not bound to instances of the classes. they behave like top-level functions which can be called from class directly or even its instances.

this saves a lot of memory and increases performance manifold.

Conclusion : when to use static methods ?

From the above post , its has become pretty clear now that static methods are independent of the object instance and we cant manipulate instance state from a static method. So, whenever we have a method in our class that doesn’t do any thing with instance state or use the self keyword . we can convert it into a static method and improve performance and memory efficiency.

Thanks for reading till end 😊😊

Stay connected

Some Thing to say ?