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
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
A voting comment increases the vote count for the chosen answer by one.
Upvoting a comment with a selected answer will also increase the vote count towards that answer by one.
So if you see a comment that you already agree with, you can upvote it instead of posting a new comment.
mazimir
Highly Voted 3 years, 1 month agozantrz
Most Recent 9 months, 3 weeks agokstr
1 year, 4 months agokontra
1 year, 6 months agojdskjksdkj
1 year, 6 months agokoenable
1 year, 3 months agotanhuynh10
1 year, 7 months agomacxsz
2 years, 6 months agovlobachevsky
3 years, 1 month ago