Question 29
What is the output of the following code?
Hint
Class C inherits from B, which inherits from A.
Since all classes A, B, and C have the same whoami() method, how does it get overridden at each child class?
Solution
When creating an object (as an instance of a class), the associated class constructor is invoked immediately.
When creating an object of class C with C('Peter'), an attempt is made to invoke the C's constructor (i.e., the dunder method __init__()).
Just by solely looking at C, there is no __init__() dunder method in it, but it does inherit that of class B, which is inherited from class A.
A's constructor initializes a class member called name.
Using this constructor, C's name class member is initialized to be 'Peter'.
Now comes the part where c.whoami() is executed.
By looking at C's whoami() method, we have this as output:
whoami() method of the superclass/parent class/base class (same meaning, terms used interchangably) is invoked.
If we expanded this further to include output from B's whoami() method, we have:
Expand this once again with A's whoami() method, and we get: