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.
- class A:
- __b = 2
- def __init__(self):
- self.c = 1
- def __action(self):
- pass
- object_1 = A()
(Select two answers.)
-
A
- A.b -= 1
-
B
- object__b -= 1
-
C
- object_1._A__b -= 1
-
D
- A._A__b -= 1
Reveal correct answers
Correct answers: C, D
Explanation
Topics: underscores name mangling
Try it yourself:
- class A:
- __b = 1
- def __init__(self):
- self.c = 1
- def __action(self):
- pass
- object_1 = A()
- A._A__b -= 1
- print(A._A__b ) # 0
- object_1._A__b -= 1
- print(object_1._A__b) # -1
- # A.b -= 1 # AttributeError: type object 'A' has no attribute 'b'
- # object__b -= 1 # NameError: name 'object__b' is not defined
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.
