class-method-vs-static-method-python


In this article, we will cover the basic difference between the class method vs Static method in Python and when to use the class method and static method in python.


What is Class Method in Python? 

The @classmethod decorator is a built-in function decorator that is an expression that gets evaluated after your function is defined. The result of that evaluation shadows your function definition. A class method receives the class as an implicit first argument, just like an instance method receives the instance 


Syntax Python Class Method: 

class C(object):
@classmethod
def fun(cls, arg1, arg2, ...):
....
fun: function that needs to be converted into a class method
returns: a class method for function.



What is the Static Method in Python?

A static method does not receive an implicit first argument. A static method is also a method that is bound to the class and not the object of the class. This method can’t access or modify the class state. It is present in a class because it makes sense for the method to be present in class.


Syntax Python Static Method: 

class C(object):
@staticmethod
def fun(arg1, arg2, ...):
...
returns: a static method for function fun.



When should you use class methods over static methods in Python?

Class Methods: Use when you need to access or modify the class state or when the method needs to work with class variables or other class methods.

class MyClass:
count = 0

@classmethod
def increment_count(cls):
cls.count += 1

Static Methods: Use when the method does not access or modify class or instance state, and it performs a utility function that is related to the class but does not need access to class-specific data.

class MyClass:
@staticmethod
def add(x, y):
return x + y



Note

Instance Method in Python:

Instance methods are the most common type of methods in Python classes. They are associated with instances of a class and operate on the instance’s data. When defining an instance method, the method’s first parameter is typically named self, which refers to the instance calling the method. This allows the method to access and manipulate the instance’s attributes.


class MyClass:
def instance_method(self, arg1, arg2, ...):
# Instance method logic here
pass




date:Aug. 6, 2024