Difference between Static and Class method in Python

Object oriented programming is a programming paradigm that relies on the concept of objects. These objects can have properties and methods, and can be manipulated via the language. It is sometimes referred to as “programming with objects” or just “OOP”, and emphasizes code reusability, encapsulation, information hiding, and dynamic binding of data through methods.

Methods are the function that we use to describe the behavior or objects inside a class.

There are three types of methods in Python:

  • Instance method
  • Class method
  • Static method

Instance method is the most common type of method used in Python class.

To call an instance method, you need to create an object of the class and with the help of that object you can access instance method.

On other hand, both class method and static method can be accessed directly by using class name i.e without creating object of class. Though you can also access these methods using object of a class.

Class method and static method have some fundamental differences. Let’s have a look over the difference between Class method and Static method.

Class method

  1. A class method is a method, which bounds to a class rather than object or instance of that class.
  2. Class method can be created using @classmethod decorator.
  3. It takes first parameter as cls or any variable name which points to the class itself.
  4. It can access and modify the state of the class. That will be applicable across overall class and its instances.

As you can see, in this example on initial value of x in 2.

But when we modify the value of x using class method i.e modify(), its value changes to 5, which indicates that a class method can access and modify the state of class.

Static method

  1. Static method is similar to class method, which also bounds to a class rather than object of that class.
  2. static method can be created using @staticmethod decorator.
  3. it doesn’t take any specific first parameter like as in class methods.
  4. it can not access and modify the state of the class.

Popular Posts

Author

  • Naveen Pandey Data Scientist Machine Learning Engineer

    Naveen Pandey has more than 2 years of experience in data science and machine learning. He is an experienced Machine Learning Engineer with a strong background in data analysis, natural language processing, and machine learning. Holding a Bachelor of Science in Information Technology from Sikkim Manipal University, he excels in leveraging cutting-edge technologies such as Large Language Models (LLMs), TensorFlow, PyTorch, and Hugging Face to develop innovative solutions.

    View all posts
Spread the knowledge
 
  

Leave a Reply

Your email address will not be published. Required fields are marked *