What is the difference between @classmethod, @staticmethod and an instance method?
An instance method receives self, the object. A classmethod receives cls, the class, and is commonly used for alternative constructors. A staticmethod receives neither and is just a function living in the class namespace.
Explain it simply
In a college: a student's own roll call is an instance method, since it needs that student. The admission office procedure, like "create a student from an application form", belongs to the college itself: a classmethod. A tip like "how to convert marks to a percentage" needs no student or college; it is only filed under the department for neatness: a staticmethod.
Example
class Student:
college = "NIT"
def __init__(self, name):
self.name = name
def intro(self): # needs the object
return f"{self.name} of {self.college}"
@classmethod
def from_email(cls, email): # needs the class
return cls(email.split("@")[0])
@staticmethod
def percent(marks, total): # needs neither
return marks * 100 / total
s = Student.from_email("riya@example.com")
print(s.intro()) # Output: riya of NIT
print(Student.percent(45, 60)) # Output: 75.0Because from_email uses cls, a subclass calling it creates a subclass instance.
What to say in the interview
"Instance methods get self; classmethods get cls and are good for factory constructors that also work with subclasses; staticmethods get nothing and are utility functions grouped with the class. If a method doesn't touch self or cls, I question whether it should be a static method or a plain module function."