A class method is a type of method that is bound to the class and not the instance of the class.
"@classmethod"
decorator, followed by a function definition. The first argument of the function is always "cls", which represents the class itself.Class methods are useful in several situations.
To define a class method, you simply use the "@classmethod" decorator before the method definition.
class student:
grade = 4 # default value for class variable 'grade'
def __init__(self,name,age): #setting __init__ & parameters
self.name= name
self.age= age
def get_data(self):
print(f'{self.name} is a {self.age} years old student in grade {self.grade}')
@classmethod #classMethod decorator
def update_grade(cls,grade):
cls.grade = grade
#creating instances:
st1= student('Rahul', 12)
st2= student('Harry', 12)
st3= student('Amol', 13)
st4= student('sohili', 13)
#getting student data:
st1.get_data()
st2.get_data()
student.update_grade(5) # changing value for rest of the students(instances)
st3.get_data()
st4.get_data()
# Output:
Rahul is a 12 years old student in grade 4
Harry is a 12 years old student in grade 4
Amol is a 13 years old student in grade 5
Sohili is a 13 years old student in grade 5
In this example, the "update_grade" is a class method that takes 1 argument, "grade".
It's important to note that class methods cannot modify the class in any way, they change a class variable's value.
Python class methods are a powerful tool for defining functions that operate on the class as a whole, rather than on a specific instance of the class. They are useful for creating factory methods, alternative constructors, and other types of methods that operate at the class level. With the knowledge of how to define and use class methods, you can start writing more complex and organized code in Python.