Python 101Free
CLASSES AND OOP

Properties and Encapsulation

Controlling how attributes are read and written.

SECTION 01

@property as managed attributes

@property turns a method into a read-only attribute. Callers write obj.temperature instead of obj.temperature(). The class controls what gets returned, but the public interface looks like a plain attribute.

A matching @<name>.setter lets the class run code when the attribute is assigned. This is where you put validation: rejecting impossible values, converting input units, normalizing data. The caller still writes obj.temperature = -300, and the setter decides whether to accept it.

The pattern lets you start with a plain attribute and upgrade to a managed one later, without breaking any callers. That is the main reason Python avoids the explicit getter/setter culture you see in some other languages.

python
class Celsius:
    def __init__(self, t):
        self.temperature = t   # goes through the setter

    @property
    def temperature(self):
        return self._t

    @temperature.setter
    def temperature(self, value):
        if value < -273.15:
            raise ValueError("below absolute zero")
        self._t = value
1 more section

Create a free account to access all sections and animations.

Create free accountAlready have an account? Sign in