LearnFrenzy
Sign in Take a free test

OOP in Python · Predict the Output · Question 7

A property with a setter Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

What is the output of the following Python program?

main.py
class Temperature:
    def __init__(self, c):
        self.celsius = c

    @property
    def celsius(self):
        return self._c

    @celsius.setter
    def celsius(self, value):
        self._c = max(value, -273.15)

    @property
    def fahrenheit(self):
        return self._c * 9 / 5 + 32

t = Temperature(25)
print(t.fahrenheit)
t.celsius = -500
print(t.celsius, round(t.fahrenheit, 2))
  • A 77.0 -500 -868.0
  • B 77.0 -273.15 -459.67 Correct
  • C 77 -273.15 -459.67
  • D AttributeError
Correct Answer: Option B

Even __init__ goes through the setter. Assigning -500 is clamped to absolute zero.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links