Bird
0
0

Which code correctly implements this behavior?

hard📝 Application Q15 of 15
Python - Encapsulation and Data Protection
You want to create a class Temperature that stores temperature in Celsius internally but allows getting and setting the temperature in Fahrenheit using getter and setter methods. Which code correctly implements this behavior?
Aclass Temperature: def __init__(self, celsius=0): self._celsius = celsius @property def fahrenheit(self): return (self._celsius * 9/5) + 32 @fahrenheit.setter def fahrenheit(self, value): self._celsius = (value - 32) * 5/9
Bclass Temperature: def __init__(self, fahrenheit=32): self._fahrenheit = fahrenheit @property def celsius(self): return (self._fahrenheit - 32) * 5/9 @celsius.setter def celsius(self, value): self._fahrenheit = (value * 9/5) + 32
Cclass Temperature: def __init__(self, celsius=0): self.celsius = celsius @property def fahrenheit(self): return (self.celsius * 9/5) + 32 @fahrenheit.setter def fahrenheit(self, value): self.celsius = (value - 32) * 5/9
Dclass Temperature: def __init__(self, fahrenheit=32): self.fahrenheit = fahrenheit @property def celsius(self): return (self.fahrenheit - 32) * 5/9 @celsius.setter def celsius(self, value): self.fahrenheit = (value * 9/5) + 32
Step-by-Step Solution
Solution:
  1. Step 1: Understand internal storage and interface

    The class stores temperature internally in Celsius (_celsius) but exposes Fahrenheit via getter and setter.
  2. Step 2: Check getter and setter calculations

    Getter converts Celsius to Fahrenheit; setter converts Fahrenheit to Celsius and stores it.
  3. Step 3: Verify correct use of private attribute and decorators

    class Temperature: def __init__(self, celsius=0): self._celsius = celsius @property def fahrenheit(self): return (self._celsius * 9/5) + 32 @fahrenheit.setter def fahrenheit(self, value): self._celsius = (value - 32) * 5/9 uses _celsius internally and @property/@fahrenheit.setter correctly.
  4. Final Answer:

    Option A code correctly implements the behavior -> Option A
  5. Quick Check:

    Internal Celsius, getter/setter convert Fahrenheit [OK]
Quick Trick: Store Celsius internally, convert in getter/setter for Fahrenheit [OK]
Common Mistakes:
  • Storing Fahrenheit internally instead of Celsius
  • Using public attributes without underscore
  • Mixing getter/setter names and attributes

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes