Bird
0
0

You want to create a class with a private attribute '_score' that can only be set to values between 0 and 100. Which code correctly implements this using getter and setter methods?

hard📝 Application Q8 of 15
Python - Encapsulation and Data Protection
You want to create a class with a private attribute '_score' that can only be set to values between 0 and 100. Which code correctly implements this using getter and setter methods?
Aclass Score:\n def __init__(self):\n self._score = 0\n @property\n def score(self):\n return self.score\n @score.setter\n def score(self, value):\n self._score = value
Bclass Score:\n def __init__(self):\n self.score = 0\n def get_score(self):\n return self.score\n def set_score(self, value):\n if 0 <= value <= 100:\n self.score = value\n else:\n raise ValueError('Score must be 0-100')
Cclass Score:\n def __init__(self):\n self._score = 0\n @property\n def score(self):\n return self._score\n @score.setter\n def score(self, value):\n if 0 <= value <= 100:\n self._score = value\n else:\n raise ValueError('Score must be 0-100')
Dclass Score:\n def __init__(self):\n self._score = 0\n def score(self):\n return self._score\n def score(self, value):\n if 0 <= value <= 100:\n self._score = value
Step-by-Step Solution
Solution:
  1. Step 1: Check for proper use of @property and setter

    class Score:\n def __init__(self):\n self._score = 0\n @property\n def score(self):\n return self._score\n @score.setter\n def score(self, value):\n if 0 <= value <= 100:\n self._score = value\n else:\n raise ValueError('Score must be 0-100') uses @property and @score.setter correctly with validation.
  2. Step 2: Verify validation and attribute usage

    It validates value range and assigns to private _score attribute.
  3. Final Answer:

    class Score:\n def __init__(self):\n self._score = 0\n @property\n def score(self):\n return self._score\n @score.setter\n def score(self, value):\n if 0 <= value <= 100:\n self._score = value\n else:\n raise ValueError('Score must be 0-100') -> Option C
  4. Quick Check:

    Use @property with validation in setter for controlled access [OK]
Quick Trick: Use @property and validate in setter to control attribute values [OK]
Common Mistakes:
  • Not using @property decorators
  • Assigning to property inside setter causing recursion
  • Returning property inside getter causing infinite loop

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes