Category: Python

  • 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)


  • 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”