Author: Saravana Kumar

  • Encapsulation in Python | Easy OOP Explanation for Beginners



    πŸ”Ή What is Encapsulation?

    • Encapsulation means hiding data and keeping it safe.
    • In Python, we use class to keep variables and functions together.
    • It helps to protect the data from being changed accidentally.

    πŸ“Œ Think of a capsule – it keeps medicine safely inside.
    Encapsulation keeps data and code safely inside the class.


    πŸ”Ή Why Encapsulation?

    βœ… Easy to use
    βœ… Protects data
    βœ… Only allow limited access
    βœ… Clean and secure code


    πŸ”Ή Example: Without Encapsulation

    class Student:
        def __init__(self, name, marks):
            self.name = name
            self.marks = marks
    
    s1 = Student("Arun", 85)
    print(s1.marks)  # Anyone can access and change
    
    s1.marks = 40  # Can be changed easily
    print(s1.marks)
    
    

    πŸ” Example: With Encapsulation (using private variable)

    class Student:
        def __init__(self, name, marks):
            self.name = name
            self.__marks = marks  # private variable
    
        def get_marks(self):     # getter
            return self.__marks
    
        def set_marks(self, value):  # setter
            if value >= 0 and value <= 100:
                self.__marks = value
            else:
                print("Invalid marks!")
    
    s1 = Student("Arun", 85)
    print(s1.get_marks())  # Output: 85
    
    s1.set_marks(95)       # Valid update
    print(s1.get_marks())  # Output: 95
    
    s1.set_marks(150)      # Invalid update
    
    

    πŸ”Ž What is __ (double underscore)?

    • It makes the variable private.
    • Cannot access it directly like s1.__marks
    • Must use getter and setter methods.

    🧠 Real-Life Example:

    ATM Machine:

    • You can see balance, add money, withdraw money – but you can’t open the system.
    • That is encapsulation.

    πŸ“ Practice Questions with Answers

    ❓ Q1: Create a class BankAccount with private balance. Add deposit() and get_balance() methods.

    βœ… Answer:

    class BankAccount:
        def __init__(self, balance):
            self.__balance = balance
    
        def deposit(self, amount):
            if amount > 0:
                self.__balance += amount
    
        def get_balance(self):
            return self.__balance
    
    acc = BankAccount(1000)
    acc.deposit(500)
    print("Balance:", acc.get_balance())  # Output: 1500
    
    

    ❓ Q2: Make a class Person with private age. Use set_age() to update age with condition (must be > 0).

    βœ… Answer:

    class Person:
        def __init__(self, name, age):
            self.name = name
            self.__age = age
    
        def get_age(self):
            return self.__age
    
        def set_age(self, new_age):
            if new_age > 0:
                self.__age = new_age
            else:
                print("Invalid age!")
    
    p1 = Person("Ravi", 25)
    print(p1.get_age())
    p1.set_age(-10)  # Invalid
    p1.set_age(30)   # Valid
    print(p1.get_age())  # 30
    
    

    πŸ“˜ Summary

    WordMeaning
    EncapsulationHide data inside class using private vars
    __Makes variable private
    GetterFunction to get value
    SetterFunction to set value safely

    πŸ“£ Coming Up Next:

    ➑️ Inheritance in Python | Learn How One Class Can Use Another


  • What is self in Python? | Easy Explanation with Examples



    πŸ”Ή What is self in Python?

    • self means this object.
    • It helps Python know which object we are talking about.
    • It is used inside class functions to access the object’s data and functions.

    πŸ“Œ Important Points:

    • self is not a keyword. You can name it anything (but using self is the rule).
    • It is sent automatically when you call a function using an object.

    πŸ”Ή Example 1: Using self to store data

    class Student:
        def __init__(self, name, age):
            self.name = name  # save name
            self.age = age    # save age
    
        def show(self):
            print("Name:", self.name)
            print("Age:", self.age)
    
    s1 = Student("Arun", 18)
    s1.show()
    
    

    βœ… Output:

    Name: Arun
    Age: 18
    
    

    πŸ”Ή How self works:

    Let’s understand:

    • self.name = name β†’ store the value in the object.
    • self.age = age β†’ same for age.
    • Later, inside the show() function, we again use self.name to get the data back.

    πŸ”Ή Example 2: Use self in multiple objects

    class Car:
        def __init__(self, brand):
            self.brand = brand
    
        def start(self):
            print(self.brand, "is starting...")
    
    c1 = Car("Toyota")
    c2 = Car("BMW")
    
    c1.start()  # Toyota is starting...
    c2.start()  # BMW is starting...
    
    

    πŸ‘‰ Here, self.brand is different for each object.


    πŸ”Ή Example 3: Change values using self

    class Employee:
        def __init__(self, name, salary):
            self.name = name
            self.salary = salary
    
        def change_salary(self, new_salary):
            self.salary = new_salary
    
        def show(self):
            print("Name:", self.name)
            print("Salary:", self.salary)
    
    e1 = Employee("Ravi", 30000)
    e1.change_salary(40000)
    e1.show()
    
    

    βœ… Output:

    Name: Ravi
    Salary: 40000
    
    

    πŸ“ Practice Questions with Answers

    ❓ Q1: Create a class Laptop with brand and price. Use self to store and print data.

    βœ… Answer:

    class Laptop:
        def __init__(self, brand, price):
            self.brand = brand
            self.price = price
    
        def show(self):
            print("Brand:", self.brand)
            print("Price:", self.price)
    
    l1 = Laptop("HP", 55000)
    l1.show()
    
    

    ❓ Q2: Create a class Circle with radius. Use a method to calculate area. (Area = 3.14 Γ— radius Γ— radius)

    βœ… Answer:

    class Circle:
        def __init__(self, radius):
            self.radius = radius
    
        def area(self):
            return 3.14 * self.radius * self.radius
    
    c = Circle(5)
    print("Area:", c.area())
    
    

    🧾 Summary Table

    TermMeaning
    selfRefers to current object inside a class
    UseTo access variables and methods in object

    πŸ“£ Next:

    ➑️ β€œEncapsulation in Python | Easy OOP Explanation for Beginners”


  • What is __init__() in Python? | Constructor Made Simple



    πŸ”Ή What is __init__()?

    • __init__() is a special function in a class.
    • It is called automatically when you create an object.
    • It is used to give values to the object’s variables.

    πŸ“Œ We also call it a constructor.


    πŸ”Ή Simple Example:

    class Person:
        def __init__(self, name):
            self.name = name
    
    p1 = Person("John")
    print(p1.name)  # Output: John
    
    

    🧾 What happens here?

    1. We created a class called Person.
    2. Inside the class, we wrote a __init__() function.
    3. self.name = name means we are saving the name in the object.
    4. We made an object p1 = Person("John"). It runs the __init__() and stores "John" inside it.

    πŸ”Ή What is self in __init__()?

    • self means this object.
    • Python sends it automatically to every function inside a class.
    class Student:
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
    s1 = Student("Arun", 18)
    print(s1.name)  # Arun
    print(s1.age)   # 18
    
    

    πŸ”Ή You Can Add More Than One Parameter

    class Car:
        def __init__(self, brand, year):
            self.brand = brand
            self.year = year
    
    c1 = Car("Toyota", 2020)
    print(c1.brand)  # Toyota
    print(c1.year)   # 2020
    
    

    πŸ“ Practice Questions with Answers

    ❓ Q1: Create a class Book with title and author. Use __init__() to set values and print them.

    βœ… Answer:

    class Book:
        def __init__(self, title, author):
            self.title = title
            self.author = author
    
    b1 = Book("Python Basics", "Ravi")
    print("Title:", b1.title)
    print("Author:", b1.author)
    
    

    ❓ Q2: Create a class Laptop with brand and price. Use __init__() and print details.

    βœ… Answer:

    class Laptop:
        def __init__(self, brand, price):
            self.brand = brand
            self.price = price
    
    lap1 = Laptop("Dell", 50000)
    print("Brand:", lap1.brand)
    print("Price:", lap1.price)
    
    

    πŸ”Ž Summary

    KeywordMeaning
    __init__()Constructor β€” runs when object created
    selfRefers to the current object
    ObjectA real item created from a class

    πŸ“£ Coming Next:

    ➑️ β€œWhat is self in Python? | Easy Explanation with Examples”


  • πŸ§‘β€πŸ« What is Class and Object in Python? | Simple Explanation for Beginners



    πŸ”Ή What is a Class?

    • A class is a template or design to make things (objects).
    • It tells Python what the object has (variables) and what it can do (functions).

    βœ… Example:

    class Student:
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
    

    This class is like a student form. It has:

    • name
    • age

    πŸ”Ή What is an Object?

    • An object is something real made from the class.
    • We can make many objects from one class.

    βœ… Example:

    s1 = Student("Arun", 18)
    print(s1.name)  # Output: Arun
    
    

    ➑️ s1 is an object of the class Student.


    πŸ”Ή __init__() Method

    • This is a special function in the class.
    • It runs automatically when you make an object.
    • It gives values to the object.

    βœ… Example:

    class Car:
        def __init__(self, brand):
            self.brand = brand
    
    c1 = Car("Toyota")
    print(c1.brand)  # Output: Toyota
    
    

    πŸ”Ή What is self?

    • self means this object.
    • It is used to store data inside the object.

    βœ… Example:

    class Example:
        def show(self):
            print("Hello from", self)
    
    obj = Example()
    obj.show()
    
    

    🧠 Real-Life Example

    Let’s say we want to make details of books.

    βœ… Example:

    class Book:
        def __init__(self, title, author):
            self.title = title
            self.author = author
    
    b1 = Book("Python Basics", "Ravi")
    print(b1.title)   # Python Basics
    print(b1.author)  # Ravi
    
    

    βœ… Benefits of Using Class and Object

    Why we use OOP?Simple Explanation
    Reuse CodeUse the same class to make many objects
    Clean CodeEasy to read and update
    Better StructureKeep data and actions together

    πŸ“ Practice Questions

    Q1. Create a class Employee with name and salary. Show details.

    βœ… Answer:

    class Employee:
        def __init__(self, name, salary):
            self.name = name
            self.salary = salary
    
        def show(self):
            print("Name:", self.name)
            print("Salary:", self.salary)
    
    e1 = Employee("Meena", 25000)
    e1.show()
    
    

    🧾 Summary Table

    WordMeaning
    ClassBlueprint for making objects
    ObjectReal item created from class
    __init__()Gives values when object is created
    selfRefers to the current object

    πŸ”— Next Topic:

    ➑️ __init__() in Python – Constructor Made Simple (Coming up next)



  • What is __init__.py in Python?

    🧩 What is __init__.py in Python?


    πŸ“˜ Definition

    • __init__.py is a special Python file used to mark a folder as a Python package.
    • It tells Python: “This folder contains Python code you can import.

    πŸ“¦ Where is it used?

    It is placed inside a package folder like this:

    mypackage/
    β”œβ”€β”€ __init__.py
    β”œβ”€β”€ add.py
    β”œβ”€β”€ sub.py
    
    

    βœ… Why __init__.py is Important

    PurposeExplanation
    Marks folder as a packageWithout it, Python may not treat the folder as a package.
    Runs code when importedYou can put code in it that runs automatically.
    Helps in organizing importsMakes it easy to control what’s imported.

    βœ… Example 1: Simple Empty __init__.py

    # __init__.py
    # (can be empty)
    
    

    Usage:

    from mypackage import add
    print(add.add(2, 3))  # Output: 5
    
    

    βœ… Example 2: With Code in __init__.py

    # __init__.py
    print("Welcome to mypackage!")
    
    def greet():
        print("Hello from the package!")
    
    

    Usage:

    import mypackage
    
    mypackage.greet()
    
    

    πŸ–¨ Output:

    Welcome to mypackage!
    Hello from the package!
    
    

    βœ… Example 3: Control Imports

    If you want only certain modules to be accessible:

    # __init__.py
    __all__ = ['add']
    
    

    Now:

    from mypackage import *
    # Only add is available, not sub
    
    

    πŸ” Summary

    ItemMeaning
    __init__.pyMakes folder a package
    Can be emptyYes
    Can have codeYes (runs on import)
    Can control what to importYes with __all__

    πŸ“ Practice Task

    ❓ Create a package with:

    • __init__.py (prints “Package loaded”)
    • calc.py (function to add numbers)
    • Then import and use it.

    βœ… Answer:

    Folder: tools/

    ➑️ __init__.py

    print("Package loaded!")
    
    

    ➑️ calc.py

    def add(a, b):
        return a + b
    
    

    ➑️ Main file:

    from tools import calc
    print(calc.add(4, 5))  # Output: 9