Day #65 - Static Methods in Python

Day #65 - Static Methods in Python

ยท

3 min read

Introduction

Welcome to my 65th blog post on the Python journey. On day 65, I learned about a special method called the Static method, which has no access to class instances but still we can directly call class functions using it. Let's dive into more details and understand this method in Python.

So let's get started......

Static Method

  • These methods belong to a class rather than an instance of the class.

  • We can define them using @staticmethod decorator

  • They do not have access to class instance i.e 'self'

  • Used to create utility functions that don't need access to instance data

  • They are not called on instance of class but directly on the class itself.

Example -

In the below example, the add method is a static method of the Math class. It takes two parameters a and b and returns their sum. The method can be called on the class itself, without the need to create an instance of the class.

class Math:
  def __init__(self, num):
    self.num = num

  def addtonum(self, n):
    self.num = self.num +n

  @staticmethod
  def add(a, b):
      return a + b

# result = Math.add(1, 2)
# print(result) # Output: 3
a = Math(5)
print(a.num)
a.addtonum(6)
print(a.num)

print(Math.add(7, 2)) #calling method on the class directly

Resources Used

You can watch the video of Day#65 by clicking on the below link ๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡

Conclusion

Thanks, guys for going through this blog post. On day 65, I learned about the special utility method called static methods in Python. They don't need access to instance data and can be used directly.

Thank you if you read this post and have found this post useful. I hope you have joined me and are enjoying my magical journey of Python coding. This is it for Day #65

See you in the next one.....


About Me

Hey Guys, I am Chintan Jain from CodeWithJain. I am a trader and content creator. I am also passionate about tech and hence wanted to explore the field of tech. I always wanted to learn to code so I watched many tutorials but procrastinated practicing coding. To get into the habit of coding consistently I am starting to BLOG with HASHNODE on daily basis.

I will document my coding journey from scratch and share my daily learnings in a blog post on HASHNODE. I hope you all will enjoy my content and my coding journey.

So what are you waiting for, smash the FOLLOW and LIKE buttons and follow along my coding journey, a step to create more beautiful digital products and empower people.


ย