This content originally appeared on DEV Community and was authored by Sam Sonter
Object-oriented programming is a programming paragdigm that relies on the concept og objects.
These objects can have properties and the methods.
They are three types of methods in python:
- Instance method
- Class methed
- Static method
Instance method is the most comman 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 and Static methods have some basic differences. Let's have a look over the difference between class and static method.
Class method
A class method is a method which bounds to class rather than object or instance of the that class.
Class methods can be created using @classmethod
decorator.It takes first parameter as class 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 classs and its instances.
class classExample:
@classmethod
def class_method(css, arg1, arg2, ...):
# methody body
EXAMPLE:
class classExample:
#create variable
x = 2
@classmethod
def modify(cls):
cls.X = 5
print(cls.x)
print(classExample.x) #2
obj = classExample()
print(obj.x) #2
classExample.modify() #5
print(classExample.x) #5
print(obj.x) #5
obj.modify() #5
As you can see, in the example an initial value of x is 2.
But when we modify the value x using class method i.e
modify(), its value changes to 5, which indicates that a classs mehtod 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 @static method decorator.
It doesn't take any specific first parameter like as in class methods.
It cant access and modify the state of the class
class staticExample:
#create variable
x = 2
@staticmethod
def modify():
x = 5
print(x)
staticExample.modify()
print(staticExample.x)
obj = staticExample()
print(obj.x)
obj.modify
Sam Sonter
This content originally appeared on DEV Community and was authored by Sam Sonter
Sam Sonter | Sciencx (2022-02-04T00:25:45+00:00) The Difference between Static and Class methods in Python.. Retrieved from https://www.scien.cx/2022/02/04/the-difference-between-static-and-class-methods-in-python/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.