Bird
0
0

Consider a class that stores a temperature in Celsius internally but exposes it as Fahrenheit using property decorators. Which code correctly implements this?

hard📝 Application Q15 of 15
Python - Encapsulation and Data Protection

Consider a class that stores a temperature in Celsius internally but exposes it as Fahrenheit using property decorators. Which code correctly implements this?

class Temperature:
    def __init__(self, celsius):
        self._celsius = celsius

    @property
    def fahrenheit(self):
        # Convert Celsius to Fahrenheit
        return (self._celsius * 9/5) + 32

    @fahrenheit.setter
    def fahrenheit(self, value):
        # Convert Fahrenheit to Celsius
        self._celsius = (value - 32) * 5/9

# Usage
temp = Temperature(0)
temp.fahrenheit = 212
print(round(temp._celsius))

What is the output?

A32
B212
C0
D100
Step-by-Step Solution
Solution:
  1. Step 1: Understand property getter and setter

    The getter converts Celsius to Fahrenheit. The setter converts Fahrenheit back to Celsius and stores it.
  2. Step 2: Trace the code

    Initially, Celsius is 0. Setting temp.fahrenheit = 212 calls setter, converts 212°F to Celsius: (212-32)*5/9 = 100. Printing temp._celsius rounded gives 100.
  3. Final Answer:

    100 -> Option D
  4. Quick Check:

    Setter converts Fahrenheit to Celsius correctly [OK]
Quick Trick: Setter converts Fahrenheit to Celsius, so 212°F = 100°C [OK]
Common Mistakes:
  • Confusing getter and setter conversions
  • Printing Fahrenheit instead of Celsius
  • Not rounding the output

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes