Bird
0
0

Identify the error in this code snippet:

medium📝 Debug Q6 of 15
Python - Encapsulation and Data Protection
Identify the error in this code snippet:
class Car:
    def __init__(self):
        self._speed = 0

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

    @speed.setter
    def speed(self, value):
        if value < 0:
            raise ValueError('Speed cannot be negative')
        self.speed = value
ASetter calls itself causing infinite recursion
BMissing @property decorator
CIncorrect method name for setter
DNo error, code is correct
Step-by-Step Solution
Solution:
  1. Step 1: Analyze setter method

    Setter assigns value to self.speed, which calls setter again recursively.
  2. Step 2: Identify recursion problem

    This causes infinite recursion leading to a crash or error.
  3. Final Answer:

    Setter calls itself causing infinite recursion -> Option A
  4. Quick Check:

    Setter must assign to private attribute, not property [OK]
Quick Trick: Assign to private attribute inside setter to avoid recursion [OK]
Common Mistakes:
  • Assigning to property inside setter
  • Forgetting to use private attribute
  • Confusing decorator usage

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes