7.2.6 Encapsulation, Privacy Conventions & @property

Unit: Unit 7: Introduction to Classes • Interactive Practice

Quick Answer & Summary:

Interactive Python programming tutorial and practice in your browser.

Interactive Challenge (Run Live in Browser):

# Using @property to encapsulate and validate temperature attributes
class Temperature:
    def __init__(self, celsius):
        self._celsius = celsius  # Protected attribute by convention

    # Getter for celsius
    @property
    def celsius(self):
        return self._celsius

    # Setter with validation
    @celsius.setter
    def celsius(self, value):
        if value < -273.15:
            print("Error: Temperature below absolute zero is impossible!")
        else:
            self._celsius = value

    # Computed property (read-only)
    @property
    def fahrenheit(self):
        return (self._celsius * 9 / 5) + 32

temp = Temperature(25)
print(f"Room Temp: {temp.celsius}°C | {temp.fahrenheit}°F")

temp.celsius = 100
print(f"Boiling Point: {temp.celsius}°C | {temp.fahrenheit}°F")

temp.celsius = -300  # Triggers validation guard
Open in Live Interactive Python Sandbox →