Bird
0
0

What is the issue with this code snippet?

medium📝 Debug Q6 of 15
Python - Encapsulation and Data Protection

What is the issue with this code snippet?

class Bike:
    def __init__(self, speed):
        self._speed = speed

    @property
    def speed(self):
        return self._speed

    @speed.setter
    def speed(self, value):
        if value >= 0:
            self._speed = value

b = Bike(20)
b.speed = -5
AThe setter allows negative speed values which is invalid
BThe setter does not update the _speed attribute
CThe setter does not check for negative values properly
DThe getter method is missing
Step-by-Step Solution
Solution:
  1. Step 1: Analyze setter condition

    The setter only updates _speed if value >= 0, so negative values are ignored.
  2. Step 2: Check what happens when b.speed = -5

    Since -5 < 0, the setter does not update _speed, silently ignoring invalid input.
  3. Step 3: Identify the problem

    Setter should raise an error or handle invalid values explicitly; silently ignoring is a logical flaw.
  4. Final Answer:

    The setter does not check for negative values properly -> Option C
  5. Quick Check:

    Setter silently ignores invalid input [OK]
Quick Trick: Setter must handle invalid values explicitly [OK]
Common Mistakes:
  • Ignoring invalid setter inputs silently
  • Not raising exceptions for invalid values
  • Assuming setter always updates attribute

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes