ProgrammingPython Developer

Explain the difference between a class method (@classmethod), a static method (@staticmethod), and a regular instance method in Python. When and what to choose?

Pass interviews with Hintsage AI assistant

Answer.

  • Instance method — takes self as its first argument, which is a reference to a specific object. It is used to access/modify the state of the object.
  • @classmethod takes cls as its first argument — a reference to the class itself, not the object. It is used for factory methods or methods that operate on the class as a whole.
  • @staticmethod does not receive any implicit arguments. It is a regular function placed within the class namespace for logical grouping.

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

Trick Question.

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.

Examples of real errors due to ignorance of the subtleties of the topic.


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.