Friday , September 20 2024

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

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

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

Explanation: The customized __str__() method is called because the print() function is invoked on the object o. As there is no __str__() method within the C class, the string printed to the console (i.e. b) is produced within the B class, which means that the __str__() method has been inherited by the C class.

More Questions: Python Essentials 2 – Module 3 Test