Author: Saravana Kumar

  • 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
    
    

  • Library and Packages in Python -Introduction

    Here’s a simple explanation of Libraries and Packages in Python β€” with examples, usage, and practice questions


    πŸ“š What is a Library in Python?

    • A library is a collection of useful code (functions, classes, modules).
    • It helps you do things quickly, without writing code from scratch.
    • Python has many libraries for math, data, web, AI, etc.

    πŸ”Ή Examples of Libraries:

    LibraryUse Case
    mathMathematics (sqrt, sin)
    randomRandom numbers
    datetimeDates and time
    osOperating system tasks
    numpyNumbers, arrays
    pandasData analysis
    matplotlibDrawing graphs/plots
    requestsWeb API calls

    πŸ“¦ What is a Package?

    • A package is a folder that contains modules (Python files) and a special file called __init__.py.
    • Packages help to organize libraries better.
    • You can think of:
      • Library = a toolset
      • Package = toolbox with organized tools (modules)

    βœ… Example: Using a Library

    1. Math Library:

    import math
    print(math.pi)         # 3.1415...
    print(math.sqrt(25))   # 5.0
    
    

    2. Random Library:

    import random
    print(random.randint(1, 10))  # Random number between 1 and 10
    
    

    βœ… Using an External Library

    • Some libraries are not built-in. You need to install them using pip:
    pip install pandas
    
    

    Then use it:

    import pandas as pd
    data = pd.Series([1, 2, 3])
    print(data)
    
    

    βœ… Example: Package Structure

    Imagine this folder:

    mypackage/
        __init__.py
        add.py
        sub.py
    
    

    add.py

    def add(x, y):
        return x + y
    
    

    sub.py

    def sub(x, y):
        return x - y
    
    

    Use the Package:

    from mypackage import add, sub
    print(add.add(3, 2))
    print(sub.sub(5, 2))
    
    

    πŸ“ Practice Questions + Answers


    ❓ Q1: What is the difference between a module and a library?

    βœ… Answer:

    • A module is one Python file (.py) with code.
    • A library is a collection of modules.
    • A package is a folder containing modules.

    ❓ Q2: Use the random library to generate a number between 100 and 200.

    βœ… Code:

    import random
    print(random.randint(100, 200))
    
    

    ❓ Q3: Install and use the numpy library to create a number array.

    βœ… Code:

    pip install numpy
    
    

    βœ… Python:

    import numpy as np
    arr = np.array([10, 20, 30])
    print(arr)
    
    

    ❓ Q4: What is the role of __init__.py in a package?

    βœ… Answer:

    • It tells Python that the folder is a package.
    • It can be empty or contain startup code.

    ❓ Q5: Create your own library with a function to find the square of a number.

    βœ… Create mylib.py:

    def square(n):
        return n * n
    
    

    βœ… Use it:

    import mylib
    print(mylib.square(6))  # Output: 36
    
    

    πŸ”„ Summary Table

    TermMeaning
    ModuleSingle .py file
    LibraryCollection of modules (ready-to-use code)
    PackageFolder of modules with __init__.py
    pipPython package installer