Author: Saravana Kumar

  • Difference Between Abstraction and Encapsulation in Python | Simple Words + Examples


    πŸ”Έ Let’s Understand Both:

    FeatureAbstractionEncapsulation
    MeaningHide how it works, show only what it doesHide data and code in one unit
    FocusOn functionalityOn security and data protection
    Used withAbstract Classes, @abstractmethodPrivate variables, methods, classes
    Real-life ideaTV remote – You don’t know how it works insideMedicine capsule – It hides the inner parts

    πŸ”Ή Example of Abstraction:

    from abc import ABC, abstractmethod
    
    class Payment(ABC):
        @abstractmethod
        def pay(self):
            pass
    
    class UPI(Payment):
        def pay(self):
            print("Payment using UPI")
    
    p = UPI()
    p.pay()
    
    

    βœ… The user only knows they are using UPI. How it works inside is hidden.


    πŸ”Ή Example of Encapsulation:

    class Student:
        def __init__(self):
            self.__marks = 0  # private variable
    
        def set_marks(self, m):
            self.__marks = m
    
        def get_marks(self):
            return self.__marks
    
    s = Student()
    s.set_marks(95)
    print(s.get_marks())  # Output: 95
    
    

    βœ… The marks are protected. We use methods to access them.


    🧾 Summary Table

    Key PointAbstractionEncapsulation
    PurposeHides unnecessary detailsHides sensitive data
    How it’s doneWith abstract classes & methodsUsing private variables & methods
    Access control?NoYes (__private)
    Real-life comparisonTV remoteMedicine capsule

    🧠 Easy Tip to Remember

    • πŸ” Abstraction = “Don’t show how it works” (Focus on What)
    • πŸ”’ Encapsulation = “Don’t let others touch my data” (Focus on How safe)

    🎯 Recap in 2 Lines:

    • Abstraction hides logic
    • Encapsulation hides data

    Both help you write clean and secure code.


  • Abstraction in Python | Hiding the Complex, Showing Only the Needed



    πŸ”Ή What is Abstraction?

    Abstraction means:

    Hiding the complex details and showing only the important parts.

    It helps us to:

    • Focus on what an object does
    • Not worry about how it does it

    πŸ”Έ Real-Life Example:

    Think about a TV remote:

    • You press the power button to turn on the TV.
    • You don’t need to know how electricity flows inside.

    🟒 This is abstraction β€” showing only the button (interface), hiding the working inside.


    πŸ”Ή Abstraction in Python

    We use:

    • Abstract Base Class (ABC)
    • The abc module

    πŸ”Ή How to Use Abstraction in Python

    1. Import ABC and abstractmethod
    2. Create a class that inherits from ABC
    3. Use @abstractmethod to define abstract methods
    4. Subclass must override these methods

    πŸ”Ή Example:

    from abc import ABC, abstractmethod
    
    class Animal(ABC):  # Abstract class
        @abstractmethod
        def sound(self):  # Abstract method
            pass
    
    class Dog(Animal):
        def sound(self):
            print("Dog barks")
    
    class Cat(Animal):
        def sound(self):
            print("Cat meows")
    
    d = Dog()
    c = Cat()
    d.sound()
    c.sound()
    
    

    🟒 Output:

    Dog barks
    Cat meows
    
    

    πŸ”Ή Key Rules of Abstraction:

    • You cannot create an object of abstract class.
    • Child class must implement (override) abstract methods.
    • Abstract class can also have normal methods.

    πŸ”Ή Abstract Class with Normal Method

    from abc import ABC, abstractmethod
    
    class Vehicle(ABC):
        @abstractmethod
        def start(self):
            pass
    
        def fuel_type(self):
            print("Fuel type is petrol")
    
    class Car(Vehicle):
        def start(self):
            print("Car is starting...")
    
    c = Car()
    c.start()
    c.fuel_type()
    
    

    πŸ“ Practice Questions with Answers

    ❓ Q1: Create an abstract class Shape with abstract method area(). Implement it in Rectangle and Circle.

    βœ… Answer:

    from abc import ABC, abstractmethod
    
    class Shape(ABC):
        @abstractmethod
        def area(self):
            pass
    
    class Rectangle(Shape):
        def area(self):
            print("Area = length Γ— width")
    
    class Circle(Shape):
        def area(self):
            print("Area = Ο€ Γ— radiusΒ²")
    
    r = Rectangle()
    c = Circle()
    r.area()
    c.area()
    
    

    ❓ Q2: Make an abstract class Device with turn_on() and turn_off() methods.

    βœ… Answer:

    from abc import ABC, abstractmethod
    
    class Device(ABC):
        @abstractmethod
        def turn_on(self):
            pass
    
        @abstractmethod
        def turn_off(self):
            pass
    
    class Laptop(Device):
        def turn_on(self):
            print("Laptop is turning on")
    
        def turn_off(self):
            print("Laptop is shutting down")
    
    l = Laptop()
    l.turn_on()
    l.turn_off()
    
    

    🧾 Summary Table

    TermMeaning
    AbstractionHiding how things work, showing only what’s needed
    Abstract ClassA class with abstract methods
    Abstract MethodMethod with no body (empty function)
    @abstractmethodUsed to create abstract methods

    🎯 Quick Recap

    • Abstraction = Hiding details, showing only the essentials.
    • Use abc module, ABC, and @abstractmethod.
    • Helps write clean, structured, and safe code.

    πŸ“£ Coming Up Next:

    ➑️ Difference Between Abstraction and Encapsulation in Python (Simple Words)


  • Method Overriding in Python | Easy Explanation with Examples



    πŸ”Ή What is Method Overriding?

    Method Overriding means:

    A child class (subclass) writes its own version of a method that already exists in the parent class (superclass).

    • It helps the child class change or improve the behavior of a parent method.
    • The method name must be same in both classes.

    πŸ”Έ Real-Life Example:

    Imagine a general printer prints in black & white. But a color printer overrides that function and prints in color.


    πŸ”Ή Basic Example of Method Overriding:

    class Animal:
        def speak(self):
            print("Animal speaks")
    
    class Dog(Animal):
        def speak(self):  # Overriding the parent's method
            print("Dog barks")
    
    d = Dog()
    d.speak()  # Output: Dog barks
    
    

    βœ… Dog class has its own version of the speak() method.


    πŸ”Ή Why Use Method Overriding?

    βœ… To customize behavior
    βœ… To add extra work in child class
    βœ… To make code flexible and clean


    πŸ”Ή Calling Parent Method Using super()

    Sometimes we want to call the original (parent) method also:

    class Animal:
        def speak(self):
            print("Animal speaks")
    
    class Dog(Animal):
        def speak(self):
            super().speak()  # Call parent method
            print("Dog barks")
    
    d = Dog()
    d.speak()
    
    

    🟒 Output:

    Animal speaks
    Dog barks
    
    

    πŸ”Ή Another Example: Bank Account

    class Account:
        def show_balance(self):
            print("Balance is $1000")
    
    class SavingsAccount(Account):
        def show_balance(self):
            print("Savings balance is $1500")
    
    a = SavingsAccount()
    a.show_balance()
    
    

    πŸ“ Practice Questions with Answers

    ❓ Q1: Create a class Shape with a method draw(). Override it in Circle and Square.

    βœ… Answer:

    class Shape:
        def draw(self):
            print("Drawing a shape")
    
    class Circle(Shape):
        def draw(self):
            print("Drawing a circle")
    
    class Square(Shape):
        def draw(self):
            print("Drawing a square")
    
    c = Circle()
    s = Square()
    
    c.draw()
    s.draw()
    
    

    ❓ Q2: Create a class Employee with method work(). Override it in Manager and Developer.

    βœ… Answer:

    class Employee:
        def work(self):
            print("Employee works")
    
    class Manager(Employee):
        def work(self):
            print("Manager manages the team")
    
    class Developer(Employee):
        def work(self):
            print("Developer writes code")
    
    m = Manager()
    d = Developer()
    
    m.work()
    d.work()
    
    

    🧾 Summary

    TermMeaning
    OverridingChild class redefines parent method
    Method NameMust be the same in both classes
    Use of super()To call the parent class method from child

    🎯 Quick Recap

    • Method Overriding = Changing a parent method in the child class.
    • Useful when child class needs a different behavior.
    • super() helps to use parent’s method with the new one.


  • Polymorphism in Python | One Name, Many Uses



    πŸ”Ή What is Polymorphism?

    The word Polymorphism means:

    Poly = many, morph = form
    So, Polymorphism = many forms

    πŸ“Œ In Python, the same function or method can work in different ways depending on the object.


    πŸ”Ή Why Use Polymorphism?

    βœ… Makes code flexible
    βœ… Easy to understand and update
    βœ… Helps work with different objects in a similar way


    πŸ”Ή Example: Polymorphism with Functions

    def add(a, b):
        return a + b
    
    print(add(3, 4))        # Numbers
    print(add("Hi ", "Tom"))  # Strings
    
    

    βœ… Same function name add() works with numbers and strings β€” this is polymorphism.


    πŸ”Ή Polymorphism with Classes

    Let’s see two different classes using the same method name:

    class Dog:
        def speak(self):
            print("Dog barks")
    
    class Cat:
        def speak(self):
            print("Cat meows")
    
    def animal_sound(animal):
        animal.speak()
    
    d = Dog()
    c = Cat()
    
    animal_sound(d)
    animal_sound(c)
    
    

    βœ… Different objects (Dog, Cat) use the same method speak() in different ways.


    πŸ”Ή Polymorphism with Inheritance

    class Vehicle:
        def move(self):
            print("Vehicle is moving")
    
    class Car(Vehicle):
        def move(self):
            print("Car is driving")
    
    class Boat(Vehicle):
        def move(self):
            print("Boat is sailing")
    
    def start_trip(vehicle):
        vehicle.move()
    
    v1 = Car()
    v2 = Boat()
    
    start_trip(v1)
    start_trip(v2)
    
    

    βœ… move() method works differently for each object. This is runtime polymorphism.


    πŸ”Ή Built-in Polymorphism Example

    print(len("Python"))       # Output: 6
    print(len([1, 2, 3, 4]))    # Output: 4
    print(len((10, 20, 30)))    # Output: 3
    
    

    βœ… len() function works with string, list, tuple β€” same function name, many forms.


    πŸ“ Practice Questions with Answers

    ❓ Q1: Create a method called greet() in two classes: English and Spanish.

    βœ… Answer:

    class English:
        def greet(self):
            print("Hello")
    
    class Spanish:
        def greet(self):
            print("Hola")
    
    def say_hello(obj):
        obj.greet()
    
    e = English()
    s = Spanish()
    say_hello(e)
    say_hello(s)
    
    

    ❓ Q2: Write a function that accepts any shape class and prints area using area() method.

    βœ… Answer:

    class Circle:
        def area(self):
            print("Area of Circle: Ο€rΒ²")
    
    class Square:
        def area(self):
            print("Area of Square: sideΒ²")
    
    def print_area(shape):
        shape.area()
    
    c = Circle()
    s = Square()
    print_area(c)
    print_area(s)
    
    

    🧾 Summary Table

    TermMeaning
    PolymorphismOne method or function, many forms
    Built-inFunctions like len(), +, etc.
    User-definedMethods in different classes with same name

    🎯 Quick Recap

    • Polymorphism helps the same method name work in different ways.
    • It can be seen in:
      • Functions
      • Classes
      • Inheritance
      • Built-in functions


  • Inheritance in Python | Learn How One Class Can Use Another



    πŸ”Ή What is Inheritance?

    • Inheritance means a class (child) can use the data and functions from another class (parent).
    • This helps us reuse code and build bigger programs easily.

    πŸ“Œ Real-life example: A child gets features from parents β€” like eyes, language, habits.
    Same way, a class gets methods and data from another class.


    πŸ”Ή Why Use Inheritance?

    βœ… Reuse old code
    βœ… Add new features easily
    βœ… Clean and simple design
    βœ… Avoid writing same code again


    πŸ”Ή Basic Example: Simple Inheritance

    class Animal:
        def speak(self):
            print("Animal speaks")
    
    class Dog(Animal):  # Inherits Animal
        def bark(self):
            print("Dog barks")
    
    d = Dog()
    d.speak()  # From parent
    d.bark()   # From child
    
    

    πŸ”Έ Types of Inheritance in Python (with Examples)

    Python supports 5 types of inheritance:


    1. Single Inheritance

    One parent class β†’ One child class

    class Parent:
        def show(self):
            print("This is Parent")
    
    class Child(Parent):
        def display(self):
            print("This is Child")
    
    c = Child()
    c.show()
    c.display()
    
    

    2. Multilevel Inheritance

    Parent β†’ Child β†’ Grandchild

    class Grandfather:
        def house(self):
            print("Grandfather's house")
    
    class Father(Grandfather):
        def car(self):
            print("Father's car")
    
    class Son(Father):
        def bike(self):
            print("Son's bike")
    
    s = Son()
    s.house()
    s.car()
    s.bike()
    
    

    3. Hierarchical Inheritance

    One parent β†’ Many children

    class Animal:
        def sound(self):
            print("Animal makes sound")
    
    class Dog(Animal):
        def bark(self):
            print("Dog barks")
    
    class Cat(Animal):
        def meow(self):
            print("Cat meows")
    
    d = Dog()
    c = Cat()
    d.sound(); d.bark()
    c.sound(); c.meow()
    
    

    4. Multiple Inheritance

    Child class inherits from two or more parent classes

    class Father:
        def job(self):
            print("Father is a teacher")
    
    class Mother:
        def cook(self):
            print("Mother cooks food")
    
    class Child(Father, Mother):
        def play(self):
            print("Child plays cricket")
    
    c = Child()
    c.job()
    c.cook()
    c.play()
    
    

    5. Hybrid Inheritance

    Combination of multiple types (e.g., multiple + multilevel)

    class A:
        def a(self):
            print("Class A")
    
    class B(A):
        def b(self):
            print("Class B")
    
    class C:
        def c(self):
            print("Class C")
    
    class D(B, C):  # Combines B (from A) + C
        def d(self):
            print("Class D")
    
    obj = D()
    obj.a()
    obj.b()
    obj.c()
    obj.d()
    
    

    πŸ”Ή Using super() to Access Parent Constructor

    class Person:
        def __init__(self, name):
            self.name = name
    
    class Student(Person):
        def __init__(self, name, grade):
            super().__init__(name)  # call parent __init__
            self.grade = grade
    
    s = Student("Arun", "A")
    print(s.name, s.grade)
    
    

    πŸ“ Practice Questions with Answers

    ❓ Q1: Create a base class Vehicle, and Car, Bike should inherit from it.

    βœ… Answer:

    class Vehicle:
        def start(self):
            print("Vehicle starts")
    
    class Car(Vehicle):
        def drive(self):
            print("Car drives")
    
    class Bike(Vehicle):
        def ride(self):
            print("Bike rides")
    
    c = Car()
    c.start(); c.drive()
    
    b = Bike()
    b.start(); b.ride()
    
    

    ❓ Q2: Show multilevel inheritance using Company, Manager, Employee.

    βœ… Answer:

    class Company:
        def company_name(self):
            print("XYZ Ltd")
    
    class Manager(Company):
        def manage(self):
            print("Manages team")
    
    class Employee(Manager):
        def work(self):
            print("Works on project")
    
    e = Employee()
    e.company_name()
    e.manage()
    e.work()
    
    

    🧾 Summary Table

    Inheritance TypeStructure Example
    SingleA β†’ B
    MultilevelA β†’ B β†’ C
    HierarchicalA β†’ B, A β†’ C
    MultipleA + B β†’ C
    HybridCombination of above

    πŸ“£ Coming Up Next:

    ➑️ Polymorphism in Python | One Name, Many Forms (Easy Guide)