- LPU MCA Semester 1
- CAB106
- Unit 2
CAB106 · Unit 2: Classes and objects
Built-in class functions and object relationships
12 practice questions
Key points
- isinstance covers subclasses; type is exact
- getattr accepts a default; dir includes inherited names
- Composition owns the parts; aggregation shares them
- Use inheritance for is-a and composition for has-a
Built-in helpers inspect objects: isinstance(obj, C) tests the class or any subclass, issubclass(B, A) tests inheritance, type(x) returns the exact class, hasattr, getattr(obj, name, default), setattr and delattr work with attributes by name, dir(x) lists all names including inherited ones, and vars(x) (or x.__dict__) lists only the object's own. isinstance accepts a tuple of types, and bool is a subclass of int.
Objects relate in three main ways:
| Relationship | Meaning | Example |
|---|---|---|
| Inheritance (is-a) | Subclass specialises a parent | Dog is an Animal |
| Composition (has-a) | Parts are owned and die with the whole | House and Rooms |
| Aggregation (has-a) | Parts exist independently | Department and Teachers |
Association is the general term for any link between objects. Has-a relationships are built by storing one object in an attribute of another, and delegating work to it, as a Car calls self.engine.start(). Several wholes can share one part object in aggregation.
Exam trap: use inheritance only when the sentence 'X is a Y' is true. 'A car has an engine' calls for composition, not for deriving Car from Engine.
Try two questions
A Department holds Teacher objects, and the teachers keep existing when the Department closes. Which relationship is this?
- Composition, where the parts are destroyed with the whole
- Aggregation, where the parts exist independently of the whole
- Inheritance, where Teacher derives from Department
- Encapsulation, where every attribute is made private
Show the answer
B. Aggregation is a weaker has-a link in which the parts live on independently.
Why not A: Composition would destroy the teachers with the department.
Why not C: A teacher is not a kind of department.
Why not D: Encapsulation hides data; it does not describe containment.
A House creates its Rooms and they are destroyed when the House is destroyed. Which relationship is this?
- Aggregation, where the parts can outlive the whole
- Inheritance, where Room derives from House
- Overloading, where one name has several signatures
- Composition, where the parts cannot outlive the whole
Show the answer
D. In composition the whole owns its parts, so the parts end with it.
Why not A: In aggregation the parts exist independently of the whole.
Why not B: A room is not a kind of house, so inheritance does not fit.
Why not C: Overloading concerns method names, not containment.