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:



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_available as a private attribute and only provide a get_copies_available method without a setter.

  • B

    Change __copies_available to copies_available and make it a public attribute.

  • C

    Keep __copies_available as a private attribute and provide get_copies_available and set_copies_available methods.

  • D

    Change __copies_available to _copies_available and provide a set_copies_available method.

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.

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