1. LPU MCA Semester 1
  2. CAB106
  3. Unit 2

CAB106 · Unit 2: Classes and objects

Object references, object life cycle and garbage collection

10 practice questions

Key points

  • Names are references; b = a creates an alias
  • An object is freed when its reference count reaches zero
  • The cyclic collector frees reference cycles
  • Shallow copies share inner objects; deep copies do not

Variables are references to objects. b = a binds a second name to the same object, so a change made through one name is visible through the other. del a removes the name, not the object. a is b tests identity, while a == c tests equal contents; list(a) makes a new object.

CPython frees an object when its reference count reaches zero, and calls its __del__ method just before that. sys.getrefcount(x) reports one extra for its own argument. Objects in reference cycles are not freed by counting alone, so a cyclic garbage collector (gc.collect()) finds and frees them.

ToolResult
b = aAlias, same object
copy.copy(a)New outer object, shared inner objects
copy.deepcopy(a)Fully independent copy
x += [3]Changes the list in place
x = x + [3]Builds a new list

Exam trap: del deletes a name, not an object, and += on a list mutates it in place while x = x + y rebinds the name to a new list.

Try two questions

Question 1 · Tier 2, Understand

Which technique does CPython use first to free an object that is no longer referenced?

  1. Manual free calls written by the programmer for each object
  2. Reference counting, freeing the object when its count reaches zero
  3. Copying every live object to a fresh memory area on each run
  4. A scheduled task that deletes unused objects once every hour
Show the answer

B. CPython tracks a count of references and frees an object when it falls to zero.

Why not A: Python programmers do not free object memory by hand.

Why not C: CPython does not move all live objects on every run.

Why not D: Reclaiming is driven by references, not by a clock.

Question 2 · Tier 1, Recall

Which special method is called when an object is about to be destroyed?

  1. __exit__
  2. __delete__
  3. __close__
  4. __del__
Show the answer

D. __del__ is the finaliser called just before an object is reclaimed.

Why not A: __exit__ belongs to context managers, not object destruction.

Why not B: Python has no special method called __delete__ for this purpose.

Why not C: __close__ is not a special method of Python objects.