Python

Encapsulation & Properties

Learn to protect and validate your data. Master the @property decorator and implement proper encapsulation.

By TechCoder TeamLast updated: 2026-06-02
In a Nutshell

Learn to protect and validate your data. Master the @property decorator and implement proper encapsulation. This hands-on tutorial focuses on practical implementation of encapsulation & properties concepts.

Encapsulation & Properties

Encapsulation is one of the core principles of OOP. It means hiding the internal details of a class and controlling access to data.

Why Encapsulation?

Without encapsulation, anyone can modify your data in unexpected ways:

PYTHON PLAYGROUND
⏳ Loading editor…

Private Attributes: _ and __

Python uses naming conventions to indicate "privacy":

  • Single underscore _: "Internal use" (convention, not enforced)
  • Double underscore __: Name mangling (stronger privacy)
PYTHON PLAYGROUND
⏳ Loading editor…

Name Mangling with __

Double underscore triggers name mangling - Python renames the attribute to make it harder to access.

PYTHON PLAYGROUND
⏳ Loading editor…

The @property Decorator 🎯

Properties let you use method calls like attributes. This is the Pythonic way to implement getters and setters.

PYTHON PLAYGROUND
⏳ Loading editor…

Read-Only Properties

Omit the @setter to create a read-only property.

PYTHON PLAYGROUND
⏳ Loading editor…

Validation with Properties

Properties are perfect for validating data before storing it.

PYTHON PLAYGROUND
⏳ Loading editor…

Coding Challenge: Temperature Class 🌡️

Create a Temperature class with Celsius and Fahrenheit properties that auto-convert.

PYTHON PLAYGROUND
⏳ Loading editor…

AI Mentor

Confused about "Python encapsulation properties decorators"? Ask our AI mentor for a simplified explanation.

Quiz

Quiz

Question 1 of 5

What does a single underscore prefix (_) mean?

The attribute is completely private
It's a convention for internal use
It triggers name mangling
It makes the attribute read-only

Key Takeaways

Encapsulation hides internal details and controls access.
_attribute is a convention for "internal use".
__attribute triggers name mangling for stronger privacy.
@property creates getters (access like attributes).
@setter validates data before storing.
Read-only properties omit the setter.

What's Next?

In the next lesson, we'll learn about Inheritance & Polymorphism - how to create class hierarchies and reuse code.

Keep coding! 🚀