What is the expected output of the following code?
class A: def __init__(self, v=2): self.v = v def set(self, v=1): self.v += v return self.v a = A() b = a b.set() print(a.v)
- 3
- 1
- 2
- 0
Explanation: Let’s analyze the code:
- The A class constructor creates an instance variable named v equal to the default value passed to the constructor’s parameter v, which is 2.
- The set method takes the v variable, and returns the value passed to it incremented by 1 (v = 2 + 1 = 3)
- The a object is created from class A.
- The b object is created: it becomes a reference to object a, and it is enriched with the set property – which updates the value held by the instance variable and shared by object a.
- The updated value assigned to the instance variable v in object a is now printed to the console.
More Questions: Python Essentials 2 (PE2) Course Final Test
Please login or Register to submit your answer