Himanshu SharmaSoftware engineer
Let’s talk

Python Tutorial · Lesson 59 of 70

Python encapsulation and properties: protecting your data

Learn Python's naming conventions for private data, how name mangling works, and how @property adds validation to attributes without changing how they are used.

13 minObject-oriented programmingUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonKeep an object's data valid by using underscore conventions and @property getters and setters.

After this lesson you can stop other code from putting your objects into an invalid state, for example a bank balance below zero or a negative price.

The idea

Encapsulation means an object looks after its own data. Outsiders use a small, clear set of methods, and the object makes sure the data stays sensible. A shop's till does not let you set the total to "minus fifty" directly. You press buttons, and the till decides what is allowed.

Python is relaxed about this. It does not have private and public keywords. It relies on naming conventions and on programmers behaving sensibly.

Underscore conventions

A name that starts with one underscore means "internal: not part of the public interface". Python lets you use it anyway, but anyone who does is on their own:

python
class Account:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self._balance = balance

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("deposit must be positive")
        self._balance += amount

    def balance(self):
        return self._balance

acct = Account("Asha", 100)
acct.deposit(50)
print(acct.balance())
print(acct._balance)
result
150
150

The last line works, but it breaks the convention. Code outside the class should call balance().

Double underscore and name mangling

Two leading underscores trigger name mangling: Python quietly renames the attribute by adding the class name in front. It is designed to prevent accidental clashes between a class and its subclasses, not to hide data:

python
class Vault:
    def __init__(self):
        self.__secret = "blue door"

    def reveal(self):
        return self.__secret

vault = Vault()
print(vault.reveal())
print(vars(vault))
result
blue door
{'_Vault__secret': 'blue door'}

The attribute is stored as _Vault__secret. Anyone can still read it by that name, so do not treat it as security. For most code, a single underscore is enough.

Properties: validation without changing the syntax

Suppose you started with a plain price attribute and everyone writes item.price = 5. Later you want to reject negative prices. If you switch to set_price() methods, you must rewrite every caller. A property avoids this: the callers keep writing item.price, while your code runs behind the scenes.

python
class Item:
    def __init__(self, name, price):
        self.name = name
        self.price = price

    @property
    def price(self):
        return self._price

    @price.setter
    def price(self, value):
        if value < 0:
            raise ValueError("price cannot be negative")
        self._price = value

pen = Item("Pen", 2.5)
pen.price = 3.0
print(pen.price)
result
3.0

Two methods share the name price. The one marked @property is run when you read it. The one marked @price.setter is run when you assign to it. The real value is kept in _price. Notice that __init__ assigns to self.price, not self._price, so even the first value is validated.

Invalid values now fail loudly:

python
pen.price = -1
result
ValueError: price cannot be negative

Read-only and calculated properties

A property with no setter is read-only. This suits values that are worked out from other data:

python
class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    @property
    def area(self):
        return self.width * self.height

box = Rectangle(3, 4)
print(box.area)
box.width = 10
print(box.area)
result
12
40

The area is always up to date because it is calculated whenever you ask. Trying to assign to it fails:

python
box.area = 99
result
AttributeError: can't set attribute

How much is enough?

Do not wrap every attribute in a property. A plain attribute is simpler, and because properties keep the same syntax, you can change your mind later without breaking callers. Add a property when you need validation, a calculated value, or a read-only field.

A video version of this topic is in the video course at /learn/python/.

Common mistakes

  • Using the same name for the property and the stored value. If the getter returns self.price and the value is also stored in self.price, the property calls itself forever. Store the value in _price.
  • Forgetting the @price.setter line. The property becomes read-only and assignments fail.
  • Assigning to self._price in __init__. That skips validation for the first value.
  • Thinking double underscores are security. Mangled names are still reachable.
  • Writing getters and setters for everything. Java habits are not needed in Python. Use plain attributes until you need more.

Exercise

Write a class Student with a property mark that only accepts numbers from 0 to 100 (raise ValueError otherwise). Create a student with mark 80, set the mark to 95 and print it, then try to set it to 120 inside a try block and print the error message.

Show one possible answer
python
class Student:
    def __init__(self, name, mark):
        self.name = name
        self.mark = mark

    @property
    def mark(self):
        return self._mark

    @mark.setter
    def mark(self, value):
        if not 0 <= value <= 100:
            raise ValueError("mark must be between 0 and 100")
        self._mark = value

s = Student("Asha", 80)
s.mark = 95
print(s.mark)
try:
    s.mark = 120
except ValueError as error:
    print(error)
result
95
mark must be between 0 and 100

Key points

  • Encapsulation means keeping an object's data behind a controlled interface so that it stays valid.
  • A single leading underscore, as in _balance, tells other programmers 'internal, please do not touch'. Python does not enforce it.
  • A double leading underscore triggers name mangling, which avoids accidental clashes in subclasses. It is not real security.
  • @property turns a method into something you read like an attribute, and @name.setter lets you validate assignments.
  • Start with plain attributes and switch to properties only when you need validation or a calculated value.

Check yourself

1. What does a single leading underscore, such as _balance, mean?
2. What is the main benefit of @property?
3. A property has a getter but no setter. What happens on obj.area = 5?
4. What does self.__secret inside class Vault become?