Skip to content

Question 29

What is the output of the following code?

class A():
    def __init__(self, name):
        self.name = name
    def whoami(self):
        print(self.name)

class B(A):
    def whoami(self):
        print('B')
        super().whoami()

class C(B):
    def whoami(self):
        super().whoami()
        print('C')

c = C('Peter')
c.whoami()
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:

# super().whoami() -> refer class `B`
C
Notice that here, the 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:

B
# super().whoami() -> refer class `A`
C

Expand this once again with A's whoami() method, and we get:

B
Peter
C
Answer
B
Peter
C