Learning Sections show
@classmethod
In Python, class methods are methods that are bound to the class itself rather than to instances of the class. They can be called using the class name or an instance of the class. Class methods are defined using the @classmethod
decorator.
Example:
class Person:
# Class variable
total_people = 0
# Class method to initialize total_people
@classmethod
def increment_total_people(cls):
cls.total_people += 1
# Call class method using class name
Person.increment_total_people()
# Access class variable using class name
print(Person.total_people) # Output: 1
# Create instance of the Person class
person1 = Person()
# Call class method using instance
person1.increment_total_people()
# Access class variable using instance
print(person1.total_people) # Output: 2
Class methods are often used for factory methods that create instances of a class or for methods that need to operate on class-level data