1. LPU MCA Semester 1
  2. CAB106
  3. 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.

MethodFirst argumentTypical use
InstanceselfPer-object behaviour
ClassclsShared counters, factories
StaticnoneHelpers 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

Question 1 · Tier 1, Recall

Which decorator marks a method that receives the class itself as its first argument?

  1. @staticmethod
  2. @property
  3. @instancemethod
  4. @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.

Question 2 · Tier 2, Understand

Which kind of method receives neither self nor cls automatically?

  1. An instance method
  2. A static method
  3. A class method
  4. 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.