What is the difference between static and class method in Python?
Class method
The class method is a built-in method in python which is limited to the class but not the object of the class. It is the expression that is evaluated when we define the function. A class method receives the class as the first argument, just like the method which takes the instance.
-
It is limited to the class but not the object of the class.
-
It can modify the state of the class, which will apply to all the instances of the class.
It has access to the class state as it takes the class parameter that points to the class but not the object.
Note: We use the
@classmethoddecorator to define the class method.
Syntax
class A(object):@classmethoddef function(cls, argument1, argument2, ...):
Parameters
class: The class as an implicit first argument.
Return value
It returns a class method for the given function.
Code
Let’s discuss the basic code to understand the concept.
class Triangle:sides = 3@classmethoddef lines(cls):return cls.sidesprint(Triangle.lines())
Explanation
-
Line 1: We make a class.
-
Line 2: We initialize a variable
sides. -
Lines 4 to 6: We use the class method and call the
linesfunction. It returns the number of sides of a triangle. -
Line 8: We print its output.
Static method
A static method is the same as the class method, but it doesn’t take the implicit first argument.
-
It is limited to the class but not the object of the class.
-
It cannot modify or access the class state.
-
It is present in the class because it is a method, so it needs to be present.
Note: We use the
@staticmethoddecorator To define the static method.
Syntax
class C(object):@staticmethoddef function(argument1, argument2, ...):
Parameters
It does not receive an implicit first argument.
Return value
It returns a static method for the given function.
Code
Let’s discuss the basic code to understand the concept.
class Triangle:sides = 3@staticmethoddef info():return "Triangle has 3 sides."print(Triangle.info())
Explanation
- Line 1: We make a class.
- Line 2: We initialize a variable
sides. - Lines 4 to 6: We make a static method
infowhich prints a message. - Line 8: We call the
infofunction of a class and print its output.