Friday , September 20 2024

What will be the result of executing the following code? class A: v = 2 class B(A): v = 1 class C(B): pass o = C() print(o.v)

Questions BankCategory: Python Essentials 2What will be the result of executing the following code? class A: v = 2 class B(A): v = 1 class C(B): pass o = C() print(o.v)
What will be the result of executing the following code?

class A:
    v = 2
 
 
class B(A):
    v = 1
 
 
class C(B):
    pass
 
 
o = C()
print(o.v)
  • it will print 2
  • it will print an empty line
  • it will raise an exception
  • it will print 1

Explanation: Let’s analyze the code:

  • Class A sets the v variable to 2
  • Class B, which inherits after class A, sets the v variable to 1
  • Class C inherits from class B
  • An object o is created from class C, and the v variable is accessed and its value is printed to the screen.
  • Because the subclass B defines a class variable of the same name as existing in the superclass A, the old v value is overridden by the new one, and inherited by the C class.

More Questions: Python Essentials 2 – Module 3 Test