Class and Static Method in Python

In this class, we discuss the Class and Static Method in Python.

For Complete YouTube Video: Click Here

Class Method

The reader should have prior knowledge of decorators in python. Click here.

Take an example and understand the concept of class and static methods.

class student:
    count =0
    def __init__(self,sname):
        self.sname=sname
        self.incrementcount()
    def studentdetails(self):
        print(" Total students logged in = ",student.count)
        self.conditions()
    @classmethod
    def incrementcount(cls):
        cls.count+=1
    @staticmethod
    def conditions():
        print("you have to maintain minimum 75 percent attendance")
stu1=student("hari")
stu1.studentdetails()
stu2=student("rakesh")
stu2.studentdetails()

Output:
Total students logged in =  1
you have to maintain minimum 75 percent attendance
 Total students logged in =  2
you have to maintain minimum 75 percent attendance

In the above program, we defined a class student.

One class variable is defined, and two instance variables are defined.

The method student details. We call it the instance method. These methods have a variable self.

The variable self is referencing to object. With the variable self, we can access the instance variables.

Class method:

The class methods do not have access to instance variables.

Class methods can access the only class variable.

To define a class method, we use the decorator @classmethod.

The decorator will impose the conditions to use the defined method as a class method.

In the class method, the first parameter is cls.

The variable cls will take the reference of class. With the variable cls we can access the class variables.

Whenever we want to modify the class variable, we use class methods.

Class methods do not have access to instance variables.

Static Method

To define a static method, we use decorator @staticmethod.

The static methods do not have access to class and instance variables.

Why we use static methods?

When we want to display a message, we use static methods.

In the example shown above conditions method is a static method.

We can access these methods using object reference.

Analyze the above program for better understanding.