Friday , September 20 2024

What will be the result of executing the following code? class A: def a(self): print(‘a’) class B: def a(self): print(‘b’) class C(B,A): def c(self): self.a() o = C() o.c()

Questions BankCategory: Python Essentials 2What will be the result of executing the following code? class A: def a(self): print(‘a’) class B: def a(self): print(‘b’) class C(B,A): def c(self): self.a() o = C() o.c()
What will be the result of executing the following code?

class A:
    def a(self):
        print('a')
 
 
class B:
    def a(self):
        print('b')
 
 
class C(B,A):
    def c(self):
        self.a()
 
 
o = C()
o.c()
  • it will print c
  • it will print b
  • it will raise an exception
  • it will print a

Explanation: The code will not raise an exception because it is consistent with the Method Resolution Order (MRO).

The code will output b to the console, because class C inherits from classes B and A respectively, and if any of the subclasses defines a method of the same name as existing in the superclass – in this case, class B defines the method def a(self): – the new name overrides any of the previous instances of the name (in this case, print(‘b’) overrides print(‘a’)). As a result, even though the c method defined in class C makes a reference to the a method defined in class A, the invocation o.c() results in printing b, not a to the screen.

More Questions: Python Essentials 2 – Module 3 Test