PCAP Exam QuestionsBrowse all questions from this exam

PCAP Exam - Question 97


What is the expected behavior of the following code?

Show Answer
Correct Answer: D

D

Discussion

8 comments
Sign in to comment
mazimirOption: B
Oct 15, 2021

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

vlobachevskyOption: B
Oct 11, 2021

Correct answer is B

macxszOption: D
May 4, 2022

As it is, it raises an exception: D. it raises an exception if it was correct, foo(), answer is: B. it outputs 3

kontraOption: B
May 24, 2023

answer is B output is 3

tanhuynh10Option: B
Apr 6, 2023

The answer is B since the output is 3.

jdskjksdkjOption: B
May 11, 2023

How does the code output 3?

koenable
Aug 30, 2023

How does the code output 3? Instead of 2?

kstrOption: D
Jul 13, 2023

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

zantrzOption: B
Feb 8, 2024

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.