CodingNic

Object-Oriented Programming

Encapsulation

Object-Oriented Programming 30 min read

Encapsulation

Encapsulation

As programs grow, you do not always want data changed directly.

Sometimes values should be protected and updated in a controlled way.

This idea is called encapsulation.

What Is Encapsulation?

Encapsulation means:

  • keeping data and methods together
  • controlling access to data
  • protecting important values

In simple Python learning, we often use methods to update data instead of changing values directly.

Real Example

A bank account balance should not be changed carelessly.

Bad idea:

python
account.balance = -5000

Better idea:

Use a method like deposit() or withdraw().

Private Style Attributes

Python uses a naming style with _ or __.

Examples:

  • _balance
  • __balance

This tells other programmers:

Do not change this directly.

Example: Protected Balance

python
class BankAccount:
    def __init__(self, balance):
        self._balance = balance

account = BankAccount(100)
print(account._balance)

Output

text
100

Better: Use Methods

python
class BankAccount:
    def __init__(self, balance):
        self._balance = balance

    def deposit(self, amount):
        self._balance += amount

    def show_balance(self):
        print(self._balance)

account = BankAccount(100)
account.deposit(50)
account.show_balance()

Output

text
150

Add Rules with Methods

python
class BankAccount:
    def __init__(self, balance):
        self._balance = balance

    def withdraw(self, amount):
        if amount <= self._balance:
            self._balance -= amount
        else:
            print("Not enough money")

    def show_balance(self):
        print(self._balance)

account = BankAccount(100)
account.withdraw(30)
account.show_balance()

Output

text
70

Why This Matters

Methods let you:

  • validate values
  • stop bad changes
  • keep code organized

Common Beginner Idea

You do not need advanced privacy rules yet.

Focus on this habit:

Use methods to manage important data.

Code Along

Create a class called Wallet.

Add:

  • _money
  • add_money()
  • show_money()

Mini Challenge

Create a class called GamePlayer.

Steps:

  • Start with _health = 100
  • Create method take_damage(amount)
  • Reduce health
  • Create method show_health()

Example:

text
80

(after damage of 20)

Real World Use Case

Apps use encapsulation for balances, passwords, settings, stock counts, and user data.

Quiz

  1. What is encapsulation?
  2. Why use methods instead of direct changes?
  3. What does _balance suggest?
  4. Why is encapsulation useful?

Assignment

Create a StockItem class with _quantity, add_stock(), and show_stock().

Summary

You learned that encapsulation protects data by using methods to control how values are changed.