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

ExpressionSpecial 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

Question 1 · Tier 1, Recall

What does polymorphism mean in object-oriented programming?

  1. One class can have several parent classes at the same time
  2. One interface can trigger different behaviour in different classes
  3. One object can be copied several times without any extra code
  4. 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.

Question 2 · Tier 1, Recall

Which special method implements the * operator for an object?

  1. __times__
  2. __star__
  3. __mul__
  4. __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__.