What is the expected behavior of the following code?
What is the expected behavior of the following code?
D
class Class: __Var = 0 def foo(self): Class._Class__Var += 1 self.__prop = Class._Class__Var o1 = Class() o1.foo() o2 = Class() o2.foo() print(o2._Class__Var + o1._Class__prop) outputs 3 but in the snippet there is one mistake: 01.foo without brackets will raise exception
answer is B output is 3
As it is, it raises an exception: D. it raises an exception if it was correct, foo(), answer is: B. it outputs 3
Correct answer is B
The output of the given code is 3. Here's the breakdown of what happens: A class Class is defined. It has a class variable __Var which is set to 0. Note that __Var is a name mangling attribute, so it's actually named _Class__Var in the class's namespace. It has a method foo which: Increments the class variable _Class__Var by 1. Assigns the value of the incremented _Class__Var to an instance variable __prop. Note that __prop is also name-mangled to _Class__prop. An instance o1 of Class is created. The method foo is called on o1, which increments __Var and assigns the value to __prop. At this point, _Class__Var becomes 1, and __prop for o1 becomes 1. Another instance o2 of Class is created. The method foo is called on o2, which increments __Var and assigns the value to __prop. Now _Class__Var becomes 2, and __prop for o2 becomes 2. Finally, it prints the sum of _Class__Var of o2 and __prop of o1. So, 2 + 1 = 3 is printed.
D. Right answer . The variable __Var is a private class variable, so it is not accessible directly using o2._Class__Var. Similarly, __prop is an instance variable, so it is not accessible using o1._Class__prop
How does the code output 3?
How does the code output 3? Instead of 2?
The answer is B since the output is 3.