Python Tutorial 0/52 lessons ~6 min read Lesson 28

    Properties & Encapsulation

    Python doesn't enforce private attributes — convention uses _underscore.

    Course progress0%
    Focus
    8 guided sections
    Practice signal
    Examples included
    Career prep
    Foundation builder

    Introduction

    Python doesn't enforce private attributes — convention uses _underscore. Use @property for managed access without breaking callers.

    Understanding the topic

    Core concepts to understand:

    • _x — convention for internal.
    • __x — name-mangled (rarely used).
    • @property turns method into attribute.
    • @x.setter for write access.

    Syntax reference

    Visual flow / code:

    python
    class Temperature:
    def __init__(self, celsius: float):
    self._celsius = celsius
    @property
    def celsius(self) -> float:
    return self._celsius
    @celsius.setter
    def celsius(self, value: float):
    if value < -273.15:
    raise ValueError("Below absolute zero")
    self._celsius = value
    @property
    def fahrenheit(self) -> float:
    return self._celsius * 9/5 + 32
    t = Temperature(25)
    print(t.fahrenheit) # 77.0

    Execution workflow

    1Properties & Encapsulation Workflow
    1 / 4

    Step 1

    _x — convention for internal.

    Apply this step while implementing properties & encapsulation in real code.

    Real-world use

    Properties let you start with simple public attributes, then add validation / computation later without breaking your API. This is huge for library design.

    Best practices

    • Start with public attrs; add @property only when logic appears.
    • Underscore signals internal — don't enforce.

    Hands-on exercise

    Interview preparation — practice these questions:

    • What is @property?
    • Public vs private in Python?
    • Why no real private?

    Summary

    In summary: @property = invisible upgrade path. Convention > enforcement.

    Ready to mark this lesson complete?Track your journey across the entire course.