Encapsulation
Explore advanced OOP concepts.
Encapsulation is a free Python For Kids lesson on CoddyKit — lesson 4 of 5. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python For Kids learning path, one of 5 lessons in the course, and your progress syncs across the web and the CoddyKit app.
1
Encapsulation
Welcome back to the Object-Oriented Programming (OOP) lesson! Today, we'll learn about encapsulation in Python, a key concept that helps protect your data and methods within classes.

2
What is Encapsulation?
Encapsulation is the concept of bundling data (attributes) and methods (functions) that operate on that data within a single unit, known as a class. It also restricts direct access to some of an object's components, which means that the internal representation of an object is hidden from the outside.
- Data Hiding: Protecting the internal state of an object from unintended interference.
- Access Control: Defining how the data and methods can be accessed or modified.
Encapsulation ensures that objects control their own data and expose only what is necessary.
3
Access Modifiers
In Python, encapsulation is implemented using access modifiers to control the visibility of class members (attributes and methods). There are three types of access modifiers:
- Public: Accessible from anywhere.
- Protected: Accessible within the class and its subclasses.
- Private: Accessible only within the class itself.
Let's see how to use these access modifiers in Python.
4
Public Attributes and Methods
Public members are accessible from outside the class. By default, all attributes and methods are public unless specified otherwise.
Example:
# Defines the Person class with public attributes and methods
class Person:
def __init__(self, name, age):
self.name = name # Public attribute
self.age = age # Public attribute
def greet(self):
print("Hello, my name is " + self.name + "!") # Public method
# Creates an object of the Person class
person1 = Person("Alice", 30)
# Accesses public attributes and methods
print(person1.name) # Output: Alice
person1.greet() # Output: Hello, my name is Alice!
5
Protected Attributes and Methods
Protected members are indicated by a single underscore (_) prefix. They are accessible within the class and its subclasses but should not be accessed directly from outside the class.
Example:
# Defines the Employee class with protected attributes and methods
class Employee:
def __init__(self, name, salary):
self._name = name # Protected attribute
self._salary = salary # Protected attribute
def _increase_salary(self, amount):
self._salary += amount # Protected method
print(self._name + "'s new salary is " + str(self._salary))
# Creates an object of the Employee class
employee1 = Employee("Bob", 50000)
# Accesses protected attributes and methods (not recommended)
print(employee1._name) # Output: Bob
employee1._increase_salary(5000) # Output: Bob's new salary is 55000
6
Private Attributes and Methods
Private members are indicated by a double underscore (__) prefix. They are accessible only within the class itself and cannot be accessed directly from outside the class.
Example:
# Defines the BankAccount class with private attributes and methods
class BankAccount:
def __init__(self, owner, balance):
self.__owner = owner # Private attribute
self.__balance = balance # Private attribute
def deposit(self, amount):
self.__balance += amount # Modifies private attribute
print("Deposited:", amount)
self.__show_balance()
def __show_balance(self):
print("Current Balance:", self.__balance) # Private method
# Creates an object of the BankAccount class
account1 = BankAccount("Charlie", 1000)
# Attempts to access private attributes and methods (will cause errors)
# print(account1.__owner) # AttributeError
# account1.__show_balance() # AttributeError
# Uses public methods to interact with private attributes
account1.deposit(500) # Output:
# Deposited: 500
# Current Balance: 1500
7
Why Use Encapsulation?
Encapsulation provides several benefits:
- Control: Control how the data is accessed or modified.
- Security: Protect the internal state of an object from unintended changes.
- Maintainability: Makes the code easier to maintain and less prone to errors.
Encapsulation helps in building robust and secure applications.
8
Encapsulation Example: Car Class
Let's create a Car class that uses encapsulation to protect its attributes and methods.
Code:
# Defines the Car class with encapsulated attributes and methods
class Car:
def __init__(self, make, model, year):
self.make = make # Public attribute
self.model = model # Public attribute
self.__year = year # Private attribute
def get_year(self):
return self.__year # Public method to access private attribute
def set_year(self, year):
if year > 0:
self.__year = year # Public method to modify private attribute
print("Year updated to", self.__year)
else:
print("Invalid year!")
def __display_info(self):
print(self.make, self.model, self.__year) # Private method
def show_info(self):
self.__display_info() # Public method that calls a private method
# Creates an object of the Car class
car1 = Car("Tesla", "Model S", 2020)
# Accesses public attributes and methods
print(car1.make) # Output: Tesla
print(car1.get_year()) # Output: 2020
# Modifies the private attribute using a public method
car1.set_year(2021) # Output: Year updated to 2021
# Calls a public method that interacts with a private method
car1.show_info() # Output: Tesla Model S 2021
# Attempts to access private attributes and methods directly (will cause errors)
# print(car1.__year) # AttributeError
# car1.__display_info() # AttributeError
9
# Defines the Student class with encapsulated attributes
class Student:
def __init__(self, name, grade):
self.name = name # Public attribute
self.__grade = grade # Private attribute
def get_grade(self):
return self.__grade # Public method to access private attribute
def set_grade(self, grade):
if 0 <= grade <= 100:
self.__grade = grade # Updates the grade
else:
print("Invalid grade!")
# Creates an object of the Student class
student1 = Student("Diana", 85)
# Accesses and modifies the grade using public methods
print(student1.get_grade()) # Output: 85
student1.set_grade(90)
print(student1.get_grade()) # Output: 90
# Attempts to access the private attribute directly (will cause an error)
# print(student1.__grade) # AttributeError
10
Great Job!
You've learned how to use encapsulation in Python to protect your data and methods within classes. Encapsulation helps you control access to your object's data, making your programs more secure and maintainable. Keep practicing by designing classes with appropriate access modifiers to enhance your coding skills!

Frequently asked questions
Is the “Encapsulation” lesson free?
Yes — the full text of “Encapsulation” is free to read here on the web, and the Python For Kids course includes 5 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python For Kids course, upgrade to CoddyKit PRO.
What will I learn in “Encapsulation”?
Explore advanced OOP concepts. You practise Python For Kids with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Python For Kids?
No prior experience is required. Python For Kids on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 5, so you can start here or from the beginning and move at your own pace.
How long does the “Encapsulation” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Python For Kids lesson?
Yes. Every Python For Kids lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.