Lesson 50 of 60
โฎPrev Nextโฏ

PY-101 ยท Object-oriented Python

Encapsulation

โฑ 8 min ๐Ÿ Real Python 3 ๐ŸŽฌ Animated

50of 60

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    โšก The 30-second answer

    Encapsulation means an object protects its own data and only lets the outside change it in controlled ways. Python marks internal attributes with a leading underscore, such as self._balance, and @property lets you expose a value that reads like an attribute but runs checks behind the scenes. That way nobody can set a balance to -500 by accident.

    • Mark internal data with _
    • Use @property and a setter
    • Validate values on the way in

    Try it

    Watch it come alive, run it yourself, then prove it. Real Python, right on this page.

    Watch Python run the example. Every variable is a jar; watch the values change and the output appear.

    Encapsulation, running
    1. class Thermostat:
    2. def __init__(self, temp):
    3. self._temp = temp
    4. @property
    5. def temp(self):
    6. return self._temp
    7. @temp.setter
    8. def temp(self, value):
    9. if not 10 <= value <= 30:
    10. raise ValueError("temperature must be 10-30")
    11. self._temp = value
    12. t = Thermostat(22)
    13. t.temp = 25
    14. print(t.temp)
    15. try:
    16. t.temp = 99
    17. except ValueError as e:
    18. print("Rejected:", e)
    19. print(t.temp)
    Press โ–ถ to watch Python run this, one line at a time.
    1. The problemAny line of code anywhere can write account.balance = -500. One bad line and the bank is wrong. Encapsulation forces every change through a door that checks the rules.
    2. The Python ideaclass Name:Encapsulation means an object protects its own data and only lets the outside change it in controlled ways.
    3. In real lifeLibraries keep their internals in _underscore attributes, so they can change them freely between versions without breaking your code.

    Start with a question

    Any line of code anywhere can write account.balance = -500. One bad line and the bank is wrong. Encapsulation forces every change through a door that checks the rules.

    Bugs where data is changed from somewhere unexpected are the hardest to find. Encapsulation keeps changes in one place.

    Explain it like I'm 10

    It is a piggy bank with a slot: anyone can put coins in through the slot, but you cannot reach in and grab them.

    The technical explanation

    self._balance means "internal, use the methods". It is a convention every Python developer recognises.

    @property def balance(self): lets callers write acc.balance (no brackets) to read it.

    @balance.setter runs when someone writes acc.balance = x, so you can reject bad values.

    Syntax

    class Name:
        @property
        def value(self):
            return self._value
    
        @value.setter
        def value(self, v):
            ...
            self._value = v

    โ–ถ Run the example ๐ŸŽฌ Watch it come alive

    Real-world scenario

    Libraries keep their internals in _underscore attributes, so they can change them freely between versions without breaking your code.

    Ready for more?The full lesson adds the technical explanation, interview questions and quick revision.

    Test yourself

    5 questions. Get 4 right and this lesson is marked complete.

    1. 1. What does a leading underscore like _balance mean?
    2. 2. What does @property let you do?
    3. 3. When does a @value.setter run?
    4. 4. Main goal of encapsulation?
    5. 5. Can Python code still read obj._x?

    Questions people ask

    Does Python have private variables?

    Not truly. A single underscore means internal by convention. A double underscore (__x) triggers name mangling, which makes accidental access harder but not impossible.

    When should I use @property?

    When reading or setting a value needs logic (validation, conversion, or computing it from other data) but you want callers to use simple attribute syntax.

    Interview questions

    How this topic comes up in Python interviews. Answer out loud first, then open the model answer.

    beginner Does Python have private variables?

    Not truly. A single underscore means internal by convention. A double underscore (__x) triggers name mangling, which makes accidental access harder but not impossible.

    beginner When should I use @property?

    When reading or setting a value needs logic (validation, conversion, or computing it from other data) but you want callers to use simple attribute syntax.

    intermediate What does a leading underscore like _balance mean?

    Internal: please use the methods. A convention for internal data.

    intermediate What does @property let you do?

    Call a method without brackets, like an attribute. obj.value runs the getter.

    Quick revision

    Remember

    • Mark internal data with _
    • Use @property and a setter
    • Validate values on the way in
    • Python does not truly lock attributes; the underscore is a polite "please do not touch". Respect it, and add @property when rules matter.

    Syntax

    class Name:
        @property
        def value(self):
            return self._value
    
        @value.setter
        def value(self, v):
            ...
            self._value = v

    Official documentation