- LPU MCA Semester 1
- CAB106
- Unit 2
CAB106 · Unit 2: Classes and objects
Methods: instance, static and class methods
9 practice questions
Key points
- Instance methods take self; class methods take cls
- Static methods take no automatic first argument
- cls is the class the call was made on
- Class-body names are not visible as bare names in methods
An instance method takes self and works on one object. A class method, marked @classmethod, takes cls (the class the call was made on) and is used for shared state or alternative constructors such as P.origin(). A static method, marked @staticmethod, takes neither; it is a utility function grouped inside the class.
| Method | First argument | Typical use |
|---|---|---|
| Instance | self | Per-object behaviour |
| Class | cls | Shared counters, factories |
| Static | none | Helpers needing no state |
Static and class methods can be called on the class or an instance. Because cls is the class used for the call, a class method inherited by a subclass sees that subclass: B.who() returns B. Calling an instance method on the class without an object, as A.f(), raises TypeError because self is missing. Bare names defined in the class body are not visible inside method bodies; reach them with self.x, cls.x or ClassName.x.
Exam trap: static methods cannot read instance or class attributes through a bare name, and cls in an inherited class method refers to the subclass, not the parent.
Try two questions
Which decorator marks a method that receives the class itself as its first argument?
- @staticmethod
- @property
- @instancemethod
- @classmethod
Show the answer
D. A class method receives the class, conventionally named cls.
Why not A: A static method receives no automatic first argument.
Why not B: @property turns a method into a read-only attribute.
Why not C: There is no decorator named instancemethod in Python.
Which kind of method receives neither self nor cls automatically?
- An instance method
- A static method
- A class method
- A constructor
Show the answer
B. A static method behaves like a plain function placed inside the class.
Why not A: An instance method receives the object as self.
Why not C: A class method receives the class as cls.
Why not D: A constructor receives the new object as self.