PCAP 31 03 PCAP Certified Associate Python Programmer · Free Practice Question Medium

Question 46

Q696 - OOP


Given the code below,

indicate the code lines correctly decrementing the __b variable by one.



(Select two answers.)


  • A
  • B
  • C
  • D
Reveal correct answers

Correct answers: C, D

Explanation

Topics: underscores name mangling


Try it yourself:



Explanation:

With Python's Name Mangling you can bypass the privacy of variables.

You need to add an underscore and the class name before the two underscores.

https://www.geeksforgeeks.org/name-mangling-in-python/


Q696 (Please refer to this number, if you want to write me about this question.)

A. A.b -= 1 is incorrect because the __b variable is a private class variable, and trying to access it using the incorrect syntax A.b will result in an AttributeError.

B. object__b -= 1 is incorrect because the __b variable is a private class variable, and trying to access it using the incorrect syntax object__b will result in a NameError.

C.

object_1._A__b -= 1 is the correct choice because to access and modify a private class variable outside the class through an object instance, the syntax is ObjectName._ClassName__variable.

D. A._A__b -= 1 is the correct choice because the __b variable is a private class variable in class A, and to access and decrement it outside the class, the correct syntax is ClassName._ClassName__variable.

Discussion

Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.

You must be logged in to post a comment.

Preparing For

Your Certification?

255+ certifications
Detailed explanations
Free PDF samples

Has All The Questions You Need