Which method makes a + b work for objects of your class?
a + b calls a.__add__(b); if that returns NotImplemented, Python tries b.__radd__(a).
Inheritance and Polymorphism · Exercise 1 of 4
Fifteen multiple-choice questions on Python inheritance and polymorphism: overriding, super(), multilevel and multiple inheritance, the MRO, abstract classes, duck typing and operator overloading. Pick an option to check your answer instantly.
Which method makes a + b work for objects of your class?
a + b calls a.__add__(b); if that returns NotImplemented, Python tries b.__radd__(a).
Why does sum([Money(1), Money(2)]) need __radd__?
int.__add__(Money) returns NotImplemented, so Python falls back to Money.__radd__(0).
What should __add__ return when it does not support the other operand's type?
NotImplemented lets Python try the reflected method and, if that fails too, raise a proper TypeError.
A subclass defines __init__ but never calls super().__init__(). What is the usual consequence?
Python never calls a parent initialiser implicitly when the child has its own.
A Car needs an Engine. Which design is usually better?
Inheritance models "is a"; a car is not an engine.
Timed online tests with instant scores and explanations.