Python Programming - Tricky Questions - Discussion
Discussion Forum : Tricky Questions - General Questions (Q.No. 45)
45.
What will be the output of the following Python code?
class MyClass:
x = 10
obj1 = MyClass()
obj2 = MyClass()
obj1.x += 5
result = obj2.x
print(result)
Answer: Option
Explanation:
The code defines a class called
When
When
Finally,
MyClass with a class variable x set to 10.
obj1 and obj2 are both instances of the MyClass class.
When
obj1.x += 5 is executed, it modifies the x attribute of obj1 by adding 5 to its current value. Since obj1 does not have its own x attribute, it accesses the class variable x and performs the addition. As a result, obj1.x becomes 15.
When
result = obj2.x is executed, it assigns the value of obj2.x to the variable result. Since obj2 does not have its own x attribute, it also accesses the class variable x. Therefore, result is 10.
Finally,
10 is printed to the console as the output of the code.
Discussion:
Be the first person to comment on this question !
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers