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
@classmethod
decorator to define the class method.
class A(object):@classmethoddef function(cls, argument1, argument2, ...):
class
: The class as an implicit first argument.It returns a class method for the given function.
Let’s discuss the basic code to understand the concept.
class Triangle:sides = 3@classmethoddef lines(cls):return cls.sidesprint(Triangle.lines())
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 lines
function. It returns the number of sides of a triangle.
Line 8: We print its output.
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
@staticmethod
decorator To define the static method.
class C(object):@staticmethoddef function(argument1, argument2, ...):
It does not receive an implicit first argument.
It returns a static method for the given function.
Let’s discuss the basic code to understand the concept.
class Triangle:sides = 3@staticmethoddef info():return "Triangle has 3 sides."print(Triangle.info())
sides.
info
which prints a message.info
function of a class and print its output.