Junior — Middle
Explain what is meant by a class method in object-oriented programming.
sobes.tech AI
Answer from AI
A class method in Python is a method that is bound not to an instance of the class, but to the class itself. It is declared with the @classmethod decorator and takes the class as the first parameter (usually named cls). Such methods can modify the state of the class, rather than a specific object.
Example:
class MyClass:
count = 0
@classmethod
def increment_count(cls):
cls.count += 1
MyClass.increment_count()
print(MyClass.count) # Outputs 1
Here, increment_count modifies the class variable count, not an attribute of a specific object.