- LPU MCA Semester 1
- CAB106
- 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.
| Tool | Result |
|---|---|
b = a | Alias, 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
Which technique does CPython use first to free an object that is no longer referenced?
- Manual free calls written by the programmer for each object
- Reference counting, freeing the object when its count reaches zero
- Copying every live object to a fresh memory area on each run
- 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.
Which special method is called when an object is about to be destroyed?
- __exit__
- __delete__
- __close__
- __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.