Monday, July 14, 2025

๐Ÿ”’ Encapsulation in Python — Keeping Your Data Safe!

 Have you ever saved a secret in your diary with a lock? Or kept your chocolate hidden in a secret drawer? ๐Ÿซ

That’s Encapsulation in real life!

In Python, Encapsulation is a way to hide or protect data so only certain parts of your code can use or change it. It helps kyour programs safe and organized — just like putting your stuff in a locker with a key!


๐Ÿง  What is Encapsulation?

Encapsulation means bundling data and the methods that work on that data into one unit — a class.

But more importantly:

  • It hides private data

  • It only allows controlled access


๐Ÿ“ฆ Real-life Analogy

Think of a mobile phone:

  • You can use it (call, play games)

  • But you can’t open it and change the battery or circuit

That’s encapsulation — some parts are visible, and some are hidden to protect the system!


๐Ÿ Let’s Learn with Python!

๐ŸŽ’ Class with Protected Data

class Student:
def __init__(self, name, marks): self.name = name self.__marks = marks # __ makes it private def show_info(self): print(f"Name: {self.name}, Marks: {self.__marks}") def update_marks(self, new_marks): if new_marks >= 0: self.__marks = new_marks else: print("Marks can't be negative!")

๐Ÿ“š Try it Out:

s1 = Student("Aryan", 85)
s1.show_info() s1.update_marks(90) s1.show_info() # Let's try to change marks directly s1.__marks = 30 s1.show_info() # Still shows 90!

๐Ÿ’ฌ Output:

Name: Aryan, Marks: 85
Name: Aryan, Marks: 90 Name: Aryan, Marks: 90

Why didn't s1.__marks = 30 work?

Because __marks is private — only accessible inside the class!


๐Ÿ•ต️‍♂️ Accessing Private Data (Not Recommended)

You can access private data using a special trick, but it’s not safe and not advised:


print(s1._Student__marks)

This works, but we should avoid it. Instead, use getter/setter methods like update_marks().


✅ Why Use Encapsulation?

AdvantageWhat it Means
๐ŸŽฏ Controlled AccessOnly allow safe changes to data
๐Ÿ”’ Data ProtectionHide sensitive data from outside access
๐Ÿ“ฆ Clean OrganizationKeep code tidy and manageable
๐Ÿšซ Prevent MisuseStop users from breaking your class logic

๐ŸŽฎ Challenge for You!

Create a class BankAccount with:

  • Private balance

  • Method to show balance

  • Method to deposit and withdraw money

  • Prevent withdrawal if not enough money

Can you do it? Try it in your Python editor!


๐Ÿง  In Short

  • Encapsulation = Wrapping data and methods into a class

  • Use __variable to make it private

  • Control access with functions inside the class


๐Ÿ“˜ Exercise 

1. Private Attribute Creation

Create a BankAccount class with:

  • A private attribute __balance

  • A method deposit(amount) to increase balance

  • A method get_balance() to return the balance
    Task: Create an object, deposit ₹1000, and print the balance.


2. Name Mangling Access

Using the BankAccount class from Q1, try accessing the __balance attribute directly from outside the class using name mangling.
Task: Demonstrate how to read and modify it without using getter/setter.


3. Private Method

Create a Car class with:

  • A private method __engine_start() that prints "Engine started"

  • A public method start() that calls the private method
    Task: Create an object and start the car.


4. Getter & Setter Methods

Create a Student class with a private attribute __marks.

  • Write getter and setter methods for marks.

  • The setter should validate that marks are between 0 and 100, otherwise reject.
    Task: Test with valid and invalid marks.


5. Property Decorator

Rewrite Q4 using @property and @marks.setter instead of getter/setter methods.
Task: Show that student.marks = 85 works directly.


6. Encapsulation for Read-Only Attribute

Create a Book class with:

  • A private attribute __isbn

  • A read-only property isbn
    Task: Try changing ISBN from outside and show it fails.


7. Encapsulation in Inheritance

Create a Person class with a private attribute __age.
Create a Teacher class that inherits from Person.
Task: Show that Teacher objects cannot access __age directly.


8. Encapsulation with Method Overriding

Create a Device class with:

  • A private attribute __status

  • A public method turn_on() that sets status to "ON"

  • A public method turn_off() that sets status to "OFF"
    Create a subclass SmartDevice that overrides turn_on() to print "Smart device starting..." before turning on.
    Task: Demonstrate usage.


9. Encapsulation with List of Objects

Create a Library class with:

  • A private list __books

  • Methods add_book(title) and get_books()
    Task: Add books and print them without directly accessing __books.


10. Secure Attribute Access

Create a User class with:

  • Private attribute __password

  • Method set_password(pwd) that stores password only if it meets certain criteria (min 8 chars, contains number & letter)

  • Method check_password(pwd) to verify if entered password matches stored one
    Task: Test with valid and invalid passwords.


No comments:

Post a Comment

๐Ÿš€ Exploring Gemini AI and Python: A Beginner’s Guide for School Students

 Have you ever wondered how your favorite apps recognize your face, suggest videos, or even talk back like a real human? Welcome to the worl...