Example:
class MyClass: def instance_method(self): print(f"Instance: {self}") @classmethod def class_method(cls): print(f"Class: {cls.__name__}") @staticmethod def static_method(): print("Just a function") obj = MyClass() obj.instance_method() # self is obj MyClass.class_method() # cls is MyClass MyClass.static_method() # no self/cls
Common Question:
Can a class method be called through an instance? How does it differ from being called through the class itself?
Answer: Yes, a class method can be called through both an instance and the class itself. It does not matter where the call comes from — the first argument will always be the class, not the instance. When called through an instance, its class is passed as cls.
Story
In the project, all factory methods were made static (@staticmethod), but it was needed to know the name of the subclass — this turned out to be impossible. It was corrected to @classmethod to get the cls reference.
Story
To generate unique instance IDs, a regular method (self) was used, but a class method was needed since the counter should be shared for the class, not for each object.
Story
A developer placed business logic not related to the class in a static method within the class. Others could not find this function because they did not expect it in the namespace of another class, complicating maintenance.