KAHIBARO Bookshelves
Discord Login Register

13.5. Encapsulation

Understanding Encapsulation in Python

Encapsulation is about bundling data and the code that works with that data together, and controlling access to that data.

In Python classes, encapsulation usually means:

  • Keeping related data and behavior together inside a class
  • Hiding internal details that other code should not touch directly
  • Providing a clear interface (methods) for interacting with an object

Why Encapsulation Is Useful

Encapsulation helps you:

  1. Protect data from accidental changes

You decide which parts of an object can be changed directly, and which should only be changed in controlled ways.

  1. Make code easier to understand

Other parts of the program do not need to know how something is done, only how to use it.

  1. Make changes without breaking everything

You can change how a class works on the inside, as long as its public interface (methods and attributes you promised) stays the same.

A common idea in encapsulation is: “Don’t expose more than you must.”

Public, “Protected”, and “Private” (Python Style)

Python does not enforce strict access control like some other languages. Instead, it uses naming conventions to signal how attributes and methods should be used.

Public Attributes and Methods

  • No leading underscore
  • Intended to be used from outside the class

Example:

class BankAccount:
    def __init__(self, owner, balance):
        self.owner = owner      # public
        self.balance = balance  # public
    def deposit(self, amount):  # public
        self.balance += amount

Code outside the class is “allowed” to use owner, balance, and deposit:

account = BankAccount("Alice", 100)
print(account.balance)   # allowed (public)
account.deposit(50)      # allowed (public)

“Protected” (Single Underscore)

  • Starts with one underscore: _name
  • Convention: “This is internal, please don’t touch it directly.”
  • Not enforced by Python, just a warning to other programmers.

Example:

class BankAccount:
    def __init__(self, owner, balance):
        self.owner = owner
        self._balance = balance  # "protected" by convention
    def deposit(self, amount):
        self._balance += amount
    def get_balance(self):
        return self._balance

You can still access _balance from outside, but you shouldn’t:

account = BankAccount("Alice", 100)
print(account.get_balance())  # recommended
print(account._balance)       # possible, but not recommended

“Private” (Double Underscore)

  • Starts with two leading underscores: __name
  • Python does name mangling: internally renames it to include the class name.
  • Makes it harder to access from outside the class (but still not truly impossible).

Example:

class BankAccount:
    def __init__(self, owner, balance):
        self.owner = owner
        self.__balance = balance  # "private"
    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount
    def get_balance(self):
        return self.__balance

Trying to access __balance directly:

account = BankAccount("Alice", 100)
print(account.get_balance())   # OK
print(account.__balance)       # AttributeError

Internally, Python stored it as _BankAccount__balance; you could access it like this, but you should not in normal code:

print(account._BankAccount__balance)  # works, but bad practice

The idea is: double underscores strongly signal “don’t touch this from outside”.

Hiding Internal Details with Methods

Encapsulation is not just about underscores; it’s about controlling how data is changed.

Instead of letting code directly change attributes, you can:

  • Keep attributes “hidden” (with _ or __)
  • Provide methods to safely read or change them

Example: only allow valid ages for a person:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.__age = 0
        self.set_age(age)
    def set_age(self, age):
        if 0 <= age <= 120:
            self.__age = age
        else:
            print("Invalid age, keeping old value.")
    def get_age(self):
        return self.__age

Usage:

p = Person("Bob", 30)
print(p.get_age())  # 30
p.set_age(200)      # Invalid age, keeping old value.
print(p.get_age())  # still 30
# Direct access blocked:
# p.__age  -> AttributeError

The Person class encapsulates the age data and decides what values are allowed.

Encapsulation and “Information Hiding”

A typical pattern:

  • Expose a small, clear set of public methods (the interface)
  • Hide the details inside the class (private/protected attributes, helper methods)

Example: a simple counter that other code can use but not mess up:

class Counter:
    def __init__(self):
        self.__value = 0  # internal state
    def increment(self):
        self.__value += 1
    def reset(self):
        self.__value = 0
    def get_value(self):
        return self.__value

From outside:

c = Counter()
c.increment()
c.increment()
print(c.get_value())  # 2
# There is no direct way (on purpose) to set the value to something random:
# c.__value = 999  # doesn't touch the internal value; creates a new attribute

Here:

  • You only know you can increment(), reset(), and get_value()
  • You don’t care how Counter stores its value internally

Using Properties for Encapsulation

Python offers properties to make encapsulation more convenient. With a property, you can use attribute syntax (obj.x) but still have getter/setter logic behind the scenes.

Basic pattern:

  • Keep the real attribute “hidden” (e.g. __age)
  • Expose a property with the same name but with logic

Example:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.__age = 0
        self.age = age  # will use the property setter
    @property
    def age(self):
        # getter
        return self.__age
    @age.setter
    def age(self, value):
        # setter with validation
        if 0 <= value <= 120:
            self.__age = value
        else:
            print("Invalid age, keeping old value.")

Usage:

p = Person("Alice", 25)
print(p.age)   # uses getter -> 25
p.age = 30     # uses setter
print(p.age)   # 30
p.age = 200    # Invalid age, keeping old value.
print(p.age)   # still 30

From the outside, age looks like a simple attribute, but it is encapsulated with validation logic.

Practical Encapsulation Example: Bank Account

Putting it together:

  • Hide the balance
  • Validate operations
  • Provide a clear interface
class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner          # public
        self.__balance = 0          # "private"
        self.deposit(balance)       # reuse method for validation
    @property
    def balance(self):
        # read-only property (no setter)
        return self.__balance
    def deposit(self, amount):
        if amount <= 0:
            print("Deposit must be positive.")
            return
        self.__balance += amount
    def withdraw(self, amount):
        if amount <= 0:
            print("Withdrawal must be positive.")
            return
        if amount > self.__balance:
            print("Insufficient funds.")
            return
        self.__balance -= amount

Usage:

account = BankAccount("Alice", 100)
print(account.balance)     # 100
account.deposit(50)
print(account.balance)     # 150
account.withdraw(200)      # Insufficient funds.
print(account.balance)     # 150
# account.balance = 1000   # AttributeError: no setter defined
# account.__balance        # AttributeError: private attribute

In this design:

  • The internal state (__balance) is protected from direct changes
  • All changes must go through deposit or withdraw
  • The balance property provides read-only access

Encapsulation and Good Class Design

When you design classes, ask:

  1. What should other code be allowed to do with this object?
    • These become public methods and attributes.
  2. What should other code not touch directly?
    • These become “private” or “protected” attributes/methods (using _ or __).
  3. Do I need validation or rules for changes?
    • Use methods or properties instead of exposing raw attributes.

Encapsulation helps you keep your classes clean, safe, and easier to use, and it becomes more and more important as your programs grow larger.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms