- LPU MCA Semester 1
- CAB106
- Unit 3
CAB106 · Unit 3: Encapsulation, inheritance and polymorphism
Polymorphism and operator overloading
11 practice questions
Key points
- Polymorphism: same call, behaviour depends on the object
- Operators map to special methods such as __add__ and __eq__
- print uses __str__; containers use __repr__
- sum needs __radd__ because it starts from 0
Polymorphism means one interface, many behaviours. In Python it appears as method overriding and as duck typing: a function that calls a.speak() works with any object that has a speak method, whatever its class. Built-in functions are polymorphic too: len works on strings, lists and dictionaries.
Operator overloading gives operators meaning for your own classes through special methods.
| Expression | Special method |
|---|---|
a + b | __add__ (and __radd__ when the left operand is not your type) |
a * b | __mul__ |
a == b | __eq__ |
a < b | __lt__ |
len(a) | __len__ |
a[i] | __getitem__ |
str(a), print(a) | __str__ |
repr(a), list display | __repr__ |
bool(a) | __bool__ |
If a class defines __getitem__, the in operator and iteration can use it. Using + on objects with no __add__ raises TypeError. sum begins with the integer 0, so a class used with sum needs __radd__.
Exam trap: print uses __str__, but lists and the interpreter show items with __repr__.
Try two questions
What does polymorphism mean in object-oriented programming?
- One class can have several parent classes at the same time
- One interface can trigger different behaviour in different classes
- One object can be copied several times without any extra code
- One program can be split across several separate modules
Show the answer
B. Polymorphism means many forms: the same call behaves according to the object's class.
Why not A: That describes multiple inheritance.
Why not C: That describes cloning or copying.
Why not D: That describes modularity.
Which special method implements the * operator for an object?
- __times__
- __star__
- __mul__
- __multiply__
Show the answer
C. Operators map to special methods: + is __add__ and * is __mul__.
Why not A: Python has no special method called __times__.
Why not B: Python has no special method called __star__.
Why not D: The special name is __mul__, not __multiply__.