13.5Instance, Class and Static Methods
Covers IGNOU MCS-201 §13.5
Not every method needs a particular object. Some work with the class as a whole, and some need neither the object nor the class. Python distinguishes three kinds of methods for these cases.
Three kinds of methods
| Instance method | Class method | Static method | |
|---|---|---|---|
| Decorator | none | @classmethod | @staticmethod |
| First parameter | self (the object) | cls (the class) | none required |
| Can access | Instance and class variables | Class variables (through cls) | Only its own parameters |
| Called as | obj.method() | Class.method() or obj.method() | Class.method() or obj.method() |
| Typical use | Work on one object’s data | Alternative constructors; work with class-wide data | Utility functions related to the class |
A decorator is the @name line placed just above a def; it modifies the function defined below it (decorators are covered in Unit 15).
Static (class) variables
The study material calls class variables “static variables”. They have one copy shared by all objects. Read and change them through the class name, as described in the previous section.
Key takeaways
- Instance method:
self, works with one object. - Class method:
@classmethod,cls, works with the class; useful as an alternative constructor. - Static method:
@staticmethod, no special first parameter, a utility. - Class (“static”) variables are shared by all objects.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Explain with an example when you would use a static method rather than an instance method.
Show worked answer
Use a static method when the operation is related to the class but needs no data from any particular object or from the class. For example, in a Temperature class, @staticmethod def c_to_f(c): return c * 9 / 5 + 32 converts any Celsius value; it is called as Temperature.c_to_f(100) and returns 212.0. An instance method would require creating an object first for no reason.