PCPP 32 10x PCPP Certified Professional Python Programmer 1 · Free Practice Question Medium
Question 15
You are tasked with designing a system to manage a library's book inventory using Python. Each book in the inventory is represented by a Book class, which includes attributes such as title, author, and copies_available. You want to prevent external code from directly modifying the number of available copies of a book, ensuring that it is only changed through the methods provided by the class. Here is the initial code design:
- class Book:
- def __init__(self, title, author, copies_available):
- self.title = title
- self.author = author
- self.__copies_available = copies_available
- def borrow_book(self):
- if self.__copies_available > 0:
- self.__copies_available -= 1
- return True
- else:
- return False
- def return_book(self):
- self.__copies_available += 1
- def get_copies_available(self):
- return self.__copies_available
Which of the following options is the best approach to prevent external code from modifying the number of available copies directly, while still allowing it to retrieve the current count?
-
A
Keep
__copies_availableas a private attribute and only provide aget_copies_availablemethod without a setter. -
B
Change
__copies_availabletocopies_availableand make it a public attribute. -
C
Keep
__copies_availableas a private attribute and provideget_copies_availableandset_copies_availablemethods. -
D
Change
__copies_availableto_copies_availableand provide aset_copies_availablemethod.
Reveal correct answer
Correct answer: A
A.
This approach adheres to the encapsulation principle by keeping __copies_available private and preventing direct modification. Providing only a getter method allows the current number of copies to be retrieved without exposing the attribute to external modification, ensuring that changes to the attribute can only occur through the methods provided within the class (e.g., borrow_book, return_book). This helps maintain the integrity of the data.
B.
Making copies_available public exposes it to direct modification, which violates the encapsulation principle. External code could change the value of copies_available without following the rules defined in the class.
C.
Although this option maintains encapsulation, providing a setter method (set_copies_available) still allows external code to arbitrarily modify the number of copies, which can lead to inconsistent states if not used properly.
D.
Using a single underscore _ only indicates that it is intended to be protected (a convention) but does not prevent external modification. Additionally, providing a set_copies_available method opens the door for arbitrary changes, defeating the purpose of encapsulation.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
