Bird
Raised Fist0

What will be the output of the following code?

medium📝 Predict Output Q13 of Q15
Python - Encapsulation and Data Protection

What will be the output of the following code?

class Circle:
    def __init__(self, radius):
        self._radius = radius

    @property
    def radius(self):
        return self._radius

    @radius.setter
    def radius(self, value):
        if value < 0:
            self._radius = 0
        else:
            self._radius = value

c = Circle(5)
c.radius = -3
print(c.radius)
A0
B5
C-3
DAttributeError
Step-by-Step Solution
Solution:
  1. Step 1: Understand setter logic

    When setting radius, if value < 0, it sets _radius to 0, else to value.
  2. Step 2: Trace code execution

    Initial radius is 5. Then c.radius = -3 triggers setter, sets _radius to 0. Printing c.radius returns 0.
  3. Final Answer:

    0 -> Option A
  4. Quick Check:

    Setter sets negative radius to 0 [OK]
Quick Trick: Setter changes negative radius to zero, so output is 0 [OK]
Common Mistakes:
MISTAKES
  • Expecting original value 5 to remain
  • Printing -3 instead of 0
  • Confusing property with direct attribute

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes