Python course ยท Module 3: Object-Oriented Programming

Encapsulation - protecting habitats

13 min read ยท
In this lesson11

Welcome back! Darwin here with a key lesson about data security.

Imagine you're maintaining a catalog of endangered species. Data about the locations of rare animals is sensitive - you don't want poachers to have direct access! You need controlled access, validation, protection.

In OOP this mechanism is encapsulation - hiding implementation details and protecting data from unauthorized access!

What is encapsulation?

Encapsulation is one of the 4 pillars of OOP, which involves:

  1. Grouping data and methods in a single class
  2. Hiding implementation details
  3. Controlling access to data through public methods

Safari Analogy: Sensitive data about endangered species locations is protected - access only for authorized personnel, with every change logged!

# WITHOUT encapsulation - dangerous!
class Species:
    def __init__(self, name, population):
        self.name = name
        self.population = population  # Public - anyone can change!

lion = Species("Lion", 500)
lion.population = -999999  # Nobody stops this error!

# WITH encapsulation - safe!
class ProtectedSpecies:
    def __init__(self, name, population):
        self.name = name
        self.__population = population  # Private!

    def set_population(self, value):
        """Controlled access with validation"""
        if value < 0:
            raise ValueError("Population cannot be negative!")
        self.__population = value

    def get_population(self):
        return self.__population

lion = ProtectedSpecies("Lion", 500)
# lion.__population = -999  # No error, but it creates a NEW attribute; the private __population stays unchanged
lion.set_population(550)  # Works - validated!

Access conventions in Python

Python uses naming conventions to indicate access levels:

ConventionMeaningExample
namePublic - accessible from anywhereself.name
_nameProtected - only class and subclassesself._internal_id
__namePrivate - only inside the classself.__password

NOTE: In Python these are conventions, not hard restrictions! Python trusts the programmer.

Public attributes

By default all attributes are public - accessible from anywhere:

class Animal:
    def __init__(self, name, age):
        self.name = name  # Public
        self.age = age    # Public

lion = Animal("Simba", 3)

# Full access
print(lion.name)  # "Simba"
lion.age = 4      # Can modify
print(lion.age)   # 4

Use public attributes when:

  • Data is safe for direct modification
  • You don't need validation
  • It's part of the class's public API

Protected attributes - _single_underscore

Convention: An attribute with one underscore (_name) means "protected" - use only inside the class and in subclasses.

class Species:
    def __init__(self, name):
        self.name = name           # Public
        self._internal_id = 12345  # Protected - convention!

    def _calculate_risk(self):
        """Protected method - convention"""
        return self._internal_id * 2

lion = Species("Lion")

# Technically possible, but violates convention
print(lion._internal_id)  # 12345 - works, but SHOULDN'T!

# Correct usage
class EndangeredSpecies(Species):
    def get_risk(self):
        # Subclass can use _internal_id
        return self._calculate_risk()

_underscore convention:

  • Signal: "This is internal implementation, don't use directly"
  • Technical: Still accessible, Python doesn't block it
  • Documentation: Doesn't appear in help() by default

Private attributes - __double_underscore

Name Mangling: An attribute with two underscores (__name) is "private" - Python changes the name to make access harder!

class SecretData:
    def __init__(self, value):
        self.__secret = value  # Private!

    def get_secret(self):
        """Controlled access"""
        return self.__secret

data = SecretData("Top Secret")

# Direct access doesn't work
# print(data.__secret)  # AttributeError!

# Works through method
print(data.get_secret())  # "Top Secret"

# Name mangling - Python changed the name!
print(data._SecretData__secret)  # "Top Secret" - possible, but DON'T DO THIS!

Name Mangling mechanism:

  • Python changes __name to _ClassName__name
  • This hinders access but doesn't prevent it
  • Protects against accidental overriding in subclasses
class Parent:
    def __init__(self):
        self.__private = "Parent"

class Child(Parent):
    def __init__(self):
        super().__init__()
        self.__private = "Child"  # No collision!

child = Child()
print(child._Parent__private)  # "Parent"
print(child._Child__private)   # "Child"

Properties - @property

Property is an elegant way to create getters and setters that look like attributes!

Basic property (read-only)

The simplest property is a method with the @property decorator that you read without parentheses, like a regular attribute. The area and diameter of the circle are computed at the moment you read them:

class Circle:
    def __init__(self, radius):
        self.radius = radius

    @property
    def area(self):
        """Calculate area - automatically!"""
        return 3.14159 * self.radius ** 2

    @property
    def diameter(self):
        """Calculate diameter"""
        return self.radius * 2

circle = Circle(5)

# Use like an attribute, but calls a method!
print(circle.area)      # 78.53975 - looks like an attribute
print(circle.diameter)  # 10

circle.radius = 10
print(circle.area)      # 314.159 - automatically recalculated!

Property with getter and setter

Writing is handled by a second method with the same name and the @celsius.setter decorator. That is where you check the new value before it reaches the object:

class Temperature:
    def __init__(self, celsius):
        self._celsius = celsius  # Internal storage

    @property
    def celsius(self):
        """Getter - read temperature"""
        return self._celsius

    @celsius.setter
    def celsius(self, value):
        """Setter - write with validation"""
        if value < -273.15:
            raise ValueError("Temperature below absolute zero!")
        self._celsius = value

    @property
    def fahrenheit(self):
        """Automatic conversion"""
        return self._celsius * 9/5 + 32

    @fahrenheit.setter
    def fahrenheit(self, value):
        """Set via Fahrenheit"""
        self._celsius = (value - 32) * 5/9

temp = Temperature(25)

# Getter
print(temp.celsius)     # 25

# Setter with validation
temp.celsius = 30       # OK
print(temp.celsius)     # 30

# temp.celsius = -300  # ValueError: Temperature below absolute zero!

# Automatic conversion
print(temp.fahrenheit)  # 86.0
temp.fahrenheit = 32    # Set via Fahrenheit
print(temp.celsius)     # 0.0 - automatic conversion!

Read-only property

If you don't define a setter, the value can only be read. That is how a person's age works: it always follows from the birth year and the current date:

class Person:
    def __init__(self, birth_year):
        self._birth_year = birth_year

    @property
    def birth_year(self):
        """Read-only - no setter"""
        return self._birth_year

    @property
    def age(self):
        """Dynamically computed"""
        from datetime import datetime
        return datetime.now().year - self._birth_year

person = Person(1990)
print(person.age)  # depends on the current year, e.g. 36 in 2026
try:
    person.age = 40  # no setter
except AttributeError as e:
    print(e)  # property 'age' of 'Person' object has no setter

Safari example - Endangered species management system

This class combines all access levels: the names are public, the ID and status are protected, and the population, secret locations and access log are private. Properties and public methods control who can change them and how.

from datetime import datetime
from typing import List, Dict

class EndangeredSpecies:
    """
    Class managing an endangered species with full encapsulation

    Protects sensitive data about location, population, observations
    """

    # Class stores all instances
    _all_species: Dict[str, 'EndangeredSpecies'] = {}
    _next_id = 1

    def __init__(self, scientific_name, common_name, conservation_status):
        # Public data - safe to share
        self.scientific_name = scientific_name
        self.common_name = common_name

        # Protected data - _underscore convention
        self._id = EndangeredSpecies._next_id
        EndangeredSpecies._next_id += 1
        self._conservation_status = conservation_status
        self._created_at = datetime.now()

        # Private data - sensitive information
        self.__population = 0
        self.__secret_locations = []  # Locations - NOT for public!
        self.__access_log = []        # Access log

        # Register in catalog
        EndangeredSpecies._all_species[scientific_name] = self

    # === PROPERTY: Population (with validation) ===

    @property
    def population(self):
        """Read population - logged"""
        self.__log_access("population", "read")
        return self.__population

    @population.setter
    def population(self, value):
        """Write population - validation + logging"""
        self.__log_access("population", "write", f"Change from {self.__population} to {value}")

        if not isinstance(value, int):
            raise TypeError("Population must be an integer")

        if value < 0:
            raise ValueError("Population cannot be negative")

        self.__population = value
        self.__update_conservation_status()

    # === PROPERTY: Conservation Status (read-only) ===

    @property
    def conservation_status(self):
        """Conservation status - read-only"""
        return self._conservation_status

    # === PROPERTY: Threat Level (dynamically computed) ===

    @property
    def threat_level(self):
        """
        Threat level (1-10) - computed based on population
        Read-only - no setter
        """
        if self.__population == 0:
            return 10  # Critically endangered
        elif self.__population < 50:
            return 9
        elif self.__population < 250:
            return 7
        elif self.__population < 1000:
            return 5
        elif self.__population < 5000:
            return 3
        else:
            return 1  # Safe

    # === PRIVATE METHODS ===

    def __log_access(self, field, action, details=""):
        """Private method - access logging"""
        log_entry = {
            "timestamp": datetime.now(),
            "field": field,
            "action": action,
            "details": details
        }
        self.__access_log.append(log_entry)

    def __update_conservation_status(self):
        """Private method - update status based on population"""
        if self.__population == 0:
            self._conservation_status = "Extinct in the Wild"
        elif self.__population < 50:
            self._conservation_status = "Critically Endangered"
        elif self.__population < 250:
            self._conservation_status = "Endangered"
        elif self.__population < 1000:
            self._conservation_status = "Vulnerable"
        else:
            self._conservation_status = "Least Concern"

    # === PUBLIC METHODS - Controlled access ===

    def add_secret_location(self, latitude, longitude, authorization_code):
        """
        Add a sensitive location - requires authorization!

        Args:
            latitude: Latitude
            longitude: Longitude
            authorization_code: Access code (in production: hash, token, etc.)
        """
        # Authorization validation
        if authorization_code != "SAFARI_2024_SECURE":
            self.__log_access("secret_locations", "denied", "Unauthorized access")
            raise PermissionError("Unauthorized access to sensitive data!")

        # Coordinate validation
        if not (-90 <= latitude <= 90):
            raise ValueError("Invalid latitude")
        if not (-180 <= longitude <= 180):
            raise ValueError("Invalid longitude")

        location = {
            "lat": latitude,
            "lon": longitude,
            "added_at": datetime.now()
        }

        self.__secret_locations.append(location)
        self.__log_access("secret_locations", "add", f"Added location: {latitude}, {longitude}")

        return f"Location added (ID: {len(self.__secret_locations)})"

    def get_location_count(self):
        """Return number of locations without revealing details"""
        return len(self.__secret_locations)

    def get_general_area(self):
        """Return general area without precise coordinates"""
        if not self.__secret_locations:
            return "No location data"

        # Average coordinates for general area
        avg_lat = sum(loc["lat"] for loc in self.__secret_locations) / len(self.__secret_locations)
        avg_lon = sum(loc["lon"] for loc in self.__secret_locations) / len(self.__secret_locations)

        # Return rounded to 1 decimal (less precise)
        return f"Area: {avg_lat:.1f}ยฐ, {avg_lon:.1f}ยฐ"

    def get_access_log(self, authorization_code):
        """Return access log - requires authorization"""
        if authorization_code != "SAFARI_2024_SECURE":
            raise PermissionError("Unauthorized access to logs!")

        return self.__access_log.copy()  # Return a copy, not the original!

    def generate_public_report(self):
        """Public report - without sensitive data"""
        return f"""
โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•—
  {self.common_name} ({self.scientific_name})
โ• โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฃ
  Conservation status: {self.conservation_status}
  Population: {self.population} individuals
  Threat level: {self.threat_level}/10
  Known locations: {self.get_location_count()}
  General area: {self.get_general_area()}
โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
        """.strip()

    def generate_classified_report(self, authorization_code):
        """Detailed report - requires authorization"""
        if authorization_code != "SAFARI_2024_SECURE":
            raise PermissionError("Unauthorized access to classified data!")

        locations_str = "\n".join(
            f"    - Lat: {loc['lat']:.6f}, Lon: {loc['lon']:.6f} (added: {loc['added_at'].strftime('%Y-%m-%d %H:%M')})"
            for loc in self.__secret_locations
        )

        return f"""
โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•—
  CLASSIFIED REPORT - {self.common_name}
โ• โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฃ
  ID: {self._id}
  Status: {self.conservation_status}
  Population: {self.__population}
  Threat: {self.threat_level}/10

  LOCATIONS (CLASSIFIED):
{locations_str if locations_str else "    No data"}

  Data accesses: {len(self.__access_log)}
โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
        """.strip()

    # === CLASS METHODS ===

    @classmethod
    def get_species_by_threat_level(cls, min_level):
        """Return species with threat level >= min_level"""
        return [
            species for species in cls._all_species.values()
            if species.threat_level >= min_level
        ]

# === USAGE DEMONSTRATION ===

print("=== ENDANGERED SPECIES MANAGEMENT SYSTEM ===\n")

# Creating species
rhino = EndangeredSpecies(
    scientific_name="Diceros bicornis",
    common_name="Black Rhinoceros",
    conservation_status="Critically Endangered"
)

mountain_gorilla = EndangeredSpecies(
    scientific_name="Gorilla beringei beringei",
    common_name="Mountain Gorilla",
    conservation_status="Endangered"
)

# Setting population (with validation)
rhino.population = 45  # OK
mountain_gorilla.population = 880  # OK

# Attempting invalid value
try:
    rhino.population = -10  # ValueError!
except ValueError as e:
    print(f"Validation error: {e}\n")

# Adding location (requires authorization)
try:
    rhino.add_secret_location(
        latitude=-1.2345,
        longitude=36.7890,
        authorization_code="WRONG_CODE"
    )
except PermissionError as e:
    print(f"No authorization: {e}\n")

# Correct authorization
rhino.add_secret_location(-1.2345, 36.7890, "SAFARI_2024_SECURE")
rhino.add_secret_location(-1.5678, 36.9012, "SAFARI_2024_SECURE")
mountain_gorilla.add_secret_location(-1.4321, 29.6543, "SAFARI_2024_SECURE")

print("Locations added\n")

# Direct access to private data - doesn't work!
try:
    print(rhino.__population)  # AttributeError
except AttributeError:
    print("Cannot directly access __population\n")

# Access through property - works!
print(f"Rhino population (via property): {rhino.population}\n")

# Public report - safe
print("=== PUBLIC REPORT ===")
print(rhino.generate_public_report())

# Classified report - requires authorization
print("\n=== CLASSIFIED REPORT ===")
print(rhino.generate_classified_report("SAFARI_2024_SECURE"))

# Read-only properties
print(f"\n=== READ-ONLY PROPERTIES ===")
print(f"Conservation status: {rhino.conservation_status}")
print(f"Threat level: {rhino.threat_level}/10")

# Attempt to set - doesn't work!
try:
    rhino.threat_level = 1  # AttributeError - no setter!
except AttributeError as e:
    print(f"Cannot set threat_level: {e}")

# Automatic status update when population changes
print(f"\n=== AUTOMATIC UPDATE ===")
print(f"Before: population={rhino.population}, status={rhino.conservation_status}")
rhino.population = 280  # Increase population
print(f"After: population={rhino.population}, status={rhino.conservation_status}")

# Species with high threat
print(f"\n=== CRITICALLY THREATENED SPECIES ===")
critical = EndangeredSpecies.get_species_by_threat_level(7)
for species in critical:
    print(f"   {species.common_name}: Threat {species.threat_level}/10")

Advantages of encapsulation

1. Data validation

A setter can reject a value that makes no sense. A temperature below absolute zero never gets into the object:

class Temperature:
    def __init__(self):
        self.__celsius = 0

    @property
    def celsius(self):
        return self.__celsius

    @celsius.setter
    def celsius(self, value):
        if value < -273.15:
            raise ValueError("Below absolute zero!")
        self.__celsius = value

temp = Temperature()
try:
    temp.celsius = -300
except ValueError as e:
    print(e)  # Below absolute zero!

2. Access control

The account balance changes only through a method that first checks whether the withdrawal is possible:

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

    def withdraw(self, amount):
        """Controlled access"""
        if amount > self.__balance:
            raise ValueError("Insufficient funds")
        self.__balance -= amount

account = BankAccount(1000)
# account.__balance = 999999  # Creates a new attribute, the real balance stays unchanged
account.withdraw(500)  # Only through method!

3. Implementation flexibility

Code that reads circle.area doesn't know whether the area is stored or computed. That lets you change how it is calculated later without touching the rest of the program:

class Circle:
    def __init__(self, radius):
        self.__radius = radius

    @property
    def area(self):
        """User doesn't know this is computed!"""
        return 3.14159 * self.__radius ** 2

# You can change the implementation without changing the interface
circle = Circle(5)
print(circle.area)  # User uses it like an attribute

4. Hiding complexity

The private __connect() method hides the details of connecting to the database. Users of the class only know the simple query() method:

class Database:
    def __init__(self):
        self.__connection = None
        self.__cache = {}

    def __connect(self):
        """Private - user doesn't need to know the details"""
        print("Connecting to database...")

    def query(self, sql):
        """Public interface - simple"""
        if not self.__connection:
            self.__connect()
        # ... execute query

Encapsulation best practices

1. Use properties instead of getters/setters

In the Java style you write separate get_name() and set_name() methods. In Python a property gives the same result, and the code using the class looks like plain attribute access:

# Java-style - verbose
class Person:
    def __init__(self, name):
        self.__name = name

    def get_name(self):
        return self.__name

    def set_name(self, value):
        self.__name = value

# Pythonic way - elegant
class Person:
    def __init__(self, name):
        self._name = name

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

    @name.setter
    def name(self, value):
        self._name = value

2. Don't overuse private attributes

Two underscores make sense where you really protect something. A name that anyone can safely read and change can stay a plain attribute:

# Too paranoid
class Person:
    def __init__(self, name):
        self.__name = name  # Unnecessary __

# Trust conventions
class Person:
    def __init__(self, name):
        self.name = name  # Simple attribute, if you don't need protection

3. Use encapsulation for sensitive data

A password is a good candidate for a private attribute: the object keeps only its hash, compares it in check_password() and never hands the hash out.

# Protecting sensitive data. Simplified: the built-in hash() is not suitable for passwords,
# because its result changes on every run; in practice use hashlib or bcrypt
class User:
    def __init__(self, username, password):
        self.username = username         # Public
        self.__password_hash = hash(password)  # Private!

    def check_password(self, password):
        return hash(password) == self.__password_hash

Summary

In this lesson you learned:

  • What encapsulation is and why it's important
  • The difference between public, protected, and private attributes
  • The name mangling mechanism (__name)
  • Creating properties with @property, getters and setters
  • Data validation on write
  • Controlled access to sensitive information
  • Practical examples from the endangered species management system

Checkpoint

Before moving on:

  • You understand the difference between name, _name, and __name
  • You can create a property with getter and setter
  • You know when to use encapsulation
  • You understand the name mangling mechanism
  • You can validate data in a setter

Safari Analogy: Encapsulation is a protection system for sensitive data about endangered species - not everyone should have access to the locations of rare animals!

In the next lesson Darwin will teach you magic methods - hidden behaviors that make your classes work like Python's built-in types!

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. How do you mark an attribute as 'private' in Python?

  2. 2. What is the @property decorator used for?

Hands-on tasks in the game

  • Code editor

    Create an Animal(name, age) class with an age property (@property getter) that returns the age stored in self._age. If __init__ gets age < 0, raise ValueError

  • Code editor

    Add a setter (@age.setter) to the age property that changes the age but rejects negative numbers (raises ValueError)

  • Vertical ordering

    Arrange the elements of the property pattern:

  • Vertical ordering

    Arrange the property elements:

  1. QuestionPrivate Attributes
  2. QuestionProperty Decorator
  3. Coding taskProperty Getter
  4. Coding taskProperty Setter
  5. Put in orderEncapsulation - Getter/Setter
  6. Put in orderProperty Pattern

Useful articles