Friday , September 20 2024

What is the expected 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 a(self): self.a() o = C() o.c()

Questions BankCategory: Python Essentials 2What is the expected 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 a(self): self.a() o = C() o.c()
What is the expected 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 a(self):
        self.a()
 
 
o = C()
o.c()
  • The code will print a
  • The code will print c
  • The code will print b
  • The code will raise an exception

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 (PE2) Course Final Test