What will be the output of the following code?
class A: X = 0 def __init__(self,v = 0): self.Y = v A.X += v a = A() b = A(1) c = A(2) print(c.X)
- 1
- 2
- 0
- 3
Explanation: Let’s analyze the code:
- The first line of the class A definition sets the variable named X to 0. Because X is a class variable, it exists in just one copy and is stored outside any object.
- The class constructor sets the instance variable Y with the v parameter’s value, which defaults to 0.
- The class constructor sets another instance variable equal to the value of the class variable X incremented by the value assigned to v.
- When the a object is created, the X class variable stores 0.
- When the b object is created, the X class variable is incremented with the argument sent, so now X=1.
- When the c object is created, the X class variable is incremented with the argument sent, so now X=3.
- When invoking the print function, 3 is printed in the console.
More Questions: Python Essentials 2 – Module 3 Test
Please login or Register to submit your answer