Difference between Static and Class method in Python
- Naveen
- 0
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
- A class method is a method, which bounds to a class rather than object or instance of that class.
- Class method can be created using @classmethod decorator.
- It takes first parameter as cls or any variable name which points to the class itself.
- 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
- Static method is similar to class method, which also bounds to a class rather than object of that class.
- static method can be created using @staticmethod decorator.
- it doesn’t take any specific first parameter like as in class methods.
- it can not access and modify the state of the class.