Skip to contentSkip to navigation

Module 15 · Lesson 03

Encapsulation and Properties

Protect an object's data the Python way: underscore conventions, name mangling, and @property for computed, validated and read-only attributes that callers still use like plain attributes.

  • About 9 minutes
  • Builds on earlier lessons
  • 12-question quiz at the end

What you will learn

  • Underscore by agreement
  • Read like an attribute
  • A setter that checks
  • Watch a setter tidy a name

Guard your data, keep it easy to use

Python protects data by agreement and by properties, not by locking it away.

  • _internal

    One underscore says "internal, please do not touch". Nothing stops you.

  • __mangled

    Two underscores rename the attribute per class, to avoid clashes in subclasses.

  • @property

    A method you read like an attribute: box.area, with no brackets.

  • Setters

    @x.setter runs code on every assignment, so bad values can be fixed or refused.

Properties everywhere

Wherever a value must stay valid, a property can guard it.

  • Bank balancesA read-only balance changes only through deposit and withdraw.
  • Health barsA setter keeps a player's health between 0 and 100.
  • UnitsStore a distance in metres once and show kilometres as a property.
  • UsernamesA setter strips spaces and refuses an empty name.

The line inside a setter

This setter line keeps health between 0 and 100. Tap each part to see its job.

Part 1 of 4

Tap any part of the code below, or press Next.1 of 4 explored

stored value:The real value lives under an underscore name, so it does not clash with the property called health.

Attributes with code behind them

Pick an example, change it, then press Run. Say what you expect to see before you press.

Example 1 of 6Underscore by agreement

The underscore is a sign for people. Python still lets you read and change it.

Your turn: Rename _secret to __secret in the class and run again. What happens to r.__secret?

Python
class Recipe:
    def __init__(self, name):
        self.name = name
        self._secret = "a pinch of salt"

r = Recipe("soup")
print(r.name)
print(r._secret)
r._secret = "sugar"
print(r._secret)
Output
Press Run to see what it prints.

Watch a setter tidy a name

Press Step to run one line at a time. Watch the names box change.

Ready. Press Step to run the first line.

  1. class User:
  2. def __init__(self, name):
  3. self.name = name
  4. @property
  5. def name(self):
  6. return self._name
  7. @name.setter
  8. def name(self, value):
  9. self._name = value.strip().title()
  10. u = User(" ana lee ")
  11. print(u.name)
  12. u.name = "BEN"
  13. print(u.name)

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.Reading an underscore name:

class A:
    def __init__(self):
        self._code = 7
print(A()._code)

0 of 6 answered

Common property misconceptions

Each card is something learners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

Encapsulation

Encapsulation means keeping an object's internal data behind a clear outside surface. Callers use that surface (some attributes and methods); the details behind it can change without breaking them, and the object can refuse invalid changes.

Python does not lock attributes away. Instead it relies on clear conventions and on properties, under the motto "we are all consenting adults here": the class signals what is internal, and other code respects it.

One leading underscore: internal

A name that starts with a single underscore, such as self._balance, means "internal: do not use this from outside the class". Python does not stop anyone reading or writing it; it is a promise between programmers. Linters and editors warn about outside use, and from module import * skips such names in modules.

Try it 1: edit me, then Run
class Account:
    def __init__(self, owner):
        self.owner = owner        # public: part of the surface
        self._balance = 0         # internal: use the methods

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("deposit must be positive")
        self._balance += amount
Output
Press Run to see what it prints.

Two leading underscores: name mangling

A name with two leading underscores (and not two trailing ones), such as self.__pin, is renamed by Python inside the class to _ClassName__pin. This is called name mangling. Its purpose is to stop a subclass from accidentally overwriting an attribute of the same name in its parent. It is not security: anyone can still reach acc._Account__pin. Most code only needs a single underscore; use two only when you are designing a class to be subclassed by others and want to avoid clashes.

@property: attributes with code behind them

A property looks like an attribute from outside, but reading it runs a method. You make one with the @property decorator:

Try it 2: edit me, then Run
class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

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

r = Rectangle(3, 4)
print(r.area)          # 12, no brackets
r.width = 10
print(r.area)          # 40, always up to date
Output
Press Run to see what it prints.

The area is computed each time it is read, so it can never be out of date with the width and height. Callers write r.area, not r.area(), exactly as for a stored attribute.

Setters: checking new values

A property with only a getter is read-only: assigning to it raises AttributeError. To allow assignment with checks, add a setter with the decorator @<name>.setter. The real value lives in an internal attribute with an underscore:

Try it 3: edit me, then Run
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age             # goes through the setter below

    @property
    def age(self):
        return self._age

    @age.setter
    def age(self, value):
        if not isinstance(value, int) or value < 0:
            raise ValueError(f"age must be a whole number >= 0, got {value!r}")
        self._age = value

p = Person("Sam", 25)
p.age += 1                         # reads, then sets through the setter
print(p.age)                       # 26
Output
Press Run to see what it prints.

Notice that __init__ assigns self.age, not self._age. That routes the starting value through the setter too, so an object can never be created in an invalid state. Inside the getter and setter, use the underscore name; using self.age there would call the property again, endlessly.

Read-only attributes

A property without a setter gives read access while keeping writes inside the class:

Try it 4: edit me, then Run
class Account:
    def __init__(self):
        self._balance = 0

    @property
    def balance(self):
        return self._balance

    def deposit(self, amount):
        self._balance += amount
Output
Press Run to see what it prints.

acc.balance works; acc.balance = 1_000_000 raises AttributeError. The only way to change the balance is through methods that enforce the rules.

Start simple, add properties later

In some languages programmers write get_x() and set_x() methods for every field "just in case". Python does not need that. Start with a plain attribute, self.price = price. If you later need validation, turn price into a property with a setter: every caller that writes item.price or item.price = 5 keeps working unchanged. This is called a uniform interface: attributes and computed values look the same from outside.

Property or method?

Use a property for something that feels like a fact about the object: cheap to compute, no arguments, no side effects, such as area, full_name or is_empty. Use a method when the operation takes arguments, does noticeable work, changes things, or might fail for reasons beyond a bad value: withdraw(amount), save(), fetch_rates(). A good test: would a reader be surprised that reading this attribute took a second or sent a network request? Then it should be a method.

For a value that is expensive to compute and never changes, functools.cached_property computes it on first access and stores the result on the object.

Syntax

The general shape of the statements in this lesson.

syntax.py
self._internal = value          # convention: internal
self.__mangled = value          # becomes self._ClassName__mangled

class Thing:
    def __init__(self, size):
        self.size = size        # runs the setter

    @property
    def size(self):             # read: thing.size
        return self._size

    @size.setter
    def size(self, value):      # write: thing.size = value
        if value < 0:
            raise ValueError("size must be >= 0")
        self._size = value

    @property
    def double(self):           # no setter: read-only
        return self._size * 2

from functools import cached_property   # compute once, then store
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

A bank account with a read-only balance

Beginner

Write an Account whose balance can be read but not assigned, and only changes through deposit and withdraw, which refuse amounts that are not positive and withdrawals that would overdraw.

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

    @property
    def balance(self):
        return self._balance

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

    def withdraw(self, amount):
        if amount <= 0:
            raise ValueError("amount must be positive")
        if amount > self._balance:
            raise ValueError(f"only {self._balance} available")
        self._balance -= amount

acc = Account("Mia")
acc.deposit(100)
acc.withdraw(30)
print(acc.owner, acc.balance)

for action in [lambda: acc.withdraw(500), lambda: acc.deposit(-5)]:
    try:
        action()
    except ValueError as error:
        print("refused:", error)

try:
    acc.balance = 1_000_000
except AttributeError:
    print("balance cannot be assigned directly")
print("still", acc.balance)
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

The number itself lives in _balance, and the property gives read access with no setter, so assignment raises AttributeError. Every change goes through a method that checks the rules first, which means the balance can never become negative.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

Using the property name inside its own setter

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
class Pet:
    @property
    def name(self):
        return self.name

print(Pet().name)
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

RecursionError: maximum recursion depth exceeded

Write this instead

class Pet:
    def __init__(self):
        self._name = 'rex'

    @property
    def name(self):
        return self._name

print(Pet().name)

Why it happens

self.name inside the getter reads the property again, which reads it again, for ever.

In the real world

Where this shows up in software people use every day.

  1. Order lines that keep their totals honest

    E-commerce

    A shop's checkout shows each order line's quantity, price, discount and total. Bugs used to appear when one value was updated and the total was not. Now quantity and discount are validated properties and the total is computed, so the numbers on screen always agree.

    Why Python fits

    The total is never stored, so it cannot drift from the quantity and discount. Both inputs are checked by their setters, including the starting quantity passed to __init__. The checkout code just reads and assigns attributes; all the rules live in the class.

    Python
    class OrderLine:
        MAX_DISCOUNT = 50
    
        def __init__(self, product, unit_cents, quantity=1):
            self.product = product
            self._unit_cents = unit_cents
            self.quantity = quantity
            self.discount = 0
    
        @property
        def quantity(self):
            return self._quantity
    
        @quantity.setter
        def quantity(self, value):
            if not 1 <= value <= 99:
                raise ValueError("quantity must be 1 to 99")
            self._quantity = value
    
        @property
        def discount(self):
            return self._discount
    
        @discount.setter
        def discount(self, percent):
            if not 0 <= percent <= self.MAX_DISCOUNT:
                raise ValueError(f"discount must be 0 to {self.MAX_DISCOUNT}%")
            self._discount = percent
    
        @property
        def total_cents(self):
            gross = self._unit_cents * self._quantity
            return gross - gross * self._discount // 100
    
    line = OrderLine("headphones", 4999, quantity=2)
    print(line.product, line.quantity, line.total_cents)
    line.discount = 20
    line.quantity = 3
    print(line.product, line.quantity, line.total_cents)
    for change in [lambda: setattr(line, "quantity", 0), lambda: setattr(line, "discount", 75)]:
        try:
            change()
        except ValueError as error:
            print("refused:", error)
    print("total still", line.total_cents)
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

Should I write a property for every attribute?

No. Plain attributes are perfectly good Python. Add a property only when you need validation, a computed value or read-only access. Because the syntax is the same for callers, you can add it later without breaking anything.

Can a property take arguments?

No. Reading obj.total cannot pass extra values. If you need arguments, as in total(with_tax=True), write a normal method.

Where does the real value live when I use a property?

Usually in an attribute with a leading underscore, such as _age, set by the setter. Computed properties, such as an area, store nothing at all.

Is there a way to delete a property?

You can add @name.deleter to run code on del obj.name, but it is rarely needed. Most classes only use getters and setters.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/3 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 17 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.