Definition
An instance method gets the object as self. A class method, marked @classmethod, gets the class as cls and is often used as an alternative constructor. A static method, marked @staticmethod, gets neither, and is an ordinary function kept inside the class.
In simple words
Instance method: this student's result. Class method: create a student from a CSV line. Static method: a helper about marks in general, which needs no particular student.
Why it matters
You'll see all three in libraries. from_pretrained in Hugging Face, for instance, is a class method that builds a model object.
How it works
| Type | First argument | Called on | Use for |
|---|---|---|---|
| Instance | self | An object | Using this object's data |
| @classmethod | cls | The class | Other ways to build objects |
| @staticmethod | None | Either | A related helper |
In code
class Student:
pass_mark = 40
def __init__(self, name, mark):
self.name, self.mark = name, mark
def passed(self): # instance method
return self.mark >= self.pass_mark
@classmethod
def from_csv(cls, line): # alternative constructor
name, mark = line.split(",")
return cls(name, int(mark))
@staticmethod
def grade(mark): # helper: no self or cls
return "A" if mark >= 80 else "B"
riya = Student.from_csv("Riya,91")
print(riya.name, riya.passed())
print(Student.grade(91))Output
Riya True A
Common mistakes
- Forgetting self in a method's parameters, which gives a confusing argument-count error.
- Using a static method that needs the class. Use a class method so subclasses work.
Check yourself
Summary
- Instance methods use self, and class methods use cls.
- Static methods are helpers that use neither.
Finished reading?
Sources: The Python Tutorial, python.org