🔥 Advanced Level

Industry-level Python skills — Decorators, APIs, Web Scraping, Data Science & ML!

1

Advanced OOP 🏛️

✨ Magic/Dunder Methods

Python
class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return f"Vector({self.x}, {self.y})"

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

    def __len__(self):
        return int((self.x**2 + self.y**2)**0.5)

    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

v1 = Vector(3, 4)
v2 = Vector(1, 2)
print(v1 + v2)   # Vector(4, 6)
print(len(v1))    # 5

🔒 Encapsulation & Property Decorator

Python
class Temperature:
    def __init__(self, celsius=0):
        self._celsius = celsius

    @property
    def celsius(self):
        return self._celsius

    @celsius.setter
    def celsius(self, value):
        if value < -273.15:
            raise ValueError("Temperature below absolute zero!")
        self._celsius = value

    @property
    def fahrenheit(self):
        return (self._celsius * 9/5) + 32

temp = Temperature(100)
print(temp.fahrenheit)  # 212.0
temp.celsius = 37
print(f"{temp.celsius}°C = {temp.fahrenheit}°F")
# 37°C = 98.6°F

🏗️ Abstract Classes

Python
from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

    @abstractmethod
    def perimeter(self):
        pass

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14159 * self.radius ** 2

    def perimeter(self):
        return 2 * 3.14159 * self.radius

class Rectangle(Shape):
    def __init__(self, w, h):
        self.w, self.h = w, h

    def area(self):
        return self.w * self.h

    def perimeter(self):
        return 2 * (self.w + self.h)

shapes = [Circle(5), Rectangle(4, 6)]
for s in shapes:
    print(f"{s.__class__.__name__}: Area={s.area():.2f}")
# Circle: Area=78.54
# Rectangle: Area=24.00
2

Modules & Packages 📦

Python
# Built-in modules
import math
print(math.pi)          # 3.141592653589793
print(math.sqrt(144))   # 12.0
print(math.factorial(5))  # 120

import random
print(random.randint(1, 100))     # Random number
print(random.choice(["A","B","C"]))  # Random pick
items = [1, 2, 3, 4, 5]
random.shuffle(items)               # Shuffle list

import datetime
now = datetime.datetime.now()
print(now.strftime("%d-%m-%Y %H:%M"))  # 13-02-2026 00:00

import os
print(os.getcwd())        # Current directory
print(os.listdir("."))    # Files in directory

# Creating your own module — save as mymath.py
# def add(a, b): return a + b
# def multiply(a, b): return a * b
# Then: import mymath; mymath.add(5, 3)

# Installing packages with pip
# pip install requests
# pip install pandas numpy matplotlib
3

Decorators & Generators ⚙️

🎀 Decorators — Give Superpowers to Functions!

💡
Analogy: A Decorator is like a gift wrapper — it adds extra features (wrapping) to a function (gift) without changing the gift itself!
Python
import time

# Timer decorator — measures how much time a function takes
def timer(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"⏱️ {func.__name__} took {end-start:.4f}s")
        return result
    return wrapper

@timer
def slow_function():
    time.sleep(1)
    print("Done!")

slow_function()
# Done!
# ⏱️ slow_function took 1.0012s

# Logger decorator
def logger(func):
    def wrapper(*args, **kwargs):
        print(f"📝 Calling: {func.__name__}({args}, {kwargs})")
        result = func(*args, **kwargs)
        print(f"📤 Returned: {result}")
        return result
    return wrapper

@logger
def multiply(a, b):
    return a * b

multiply(5, 3)

🔄 Generators — Lazy Evaluation with yield

Python
# Generator function — memory efficient!
def countdown(n):
    while n > 0:
        yield n
        n -= 1

for num in countdown(5):
    print(num, end=" ")  # 5 4 3 2 1

# Infinite generator
def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

fib = fibonacci()
for _ in range(10):
    print(next(fib), end=" ")
# 0 1 1 2 3 5 8 13 21 34

# Generator expression (like list comprehension but lazy)
squares_gen = (x**2 for x in range(1000000))
print(next(squares_gen))  # 0  — Does not load everything in memory!
4

Lambda, Map, Filter, Reduce 🧮

Python
# Lambda — Anonymous one-liner functions
square = lambda x: x ** 2
add = lambda a, b: a + b
print(square(5))   # 25
print(add(3, 7))   # 10

# map() — Apply function to every element
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared)  # [1, 4, 9, 16, 25]

# filter() — Filter based on condition
evens = list(filter(lambda x: x % 2 == 0, range(1, 21)))
print(evens)  # [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

# reduce() — Combine all elements
from functools import reduce
total = reduce(lambda a, b: a + b, [1, 2, 3, 4, 5])
print(total)  # 15

# Practical example — Sort by second element
students = [("Rahul", 85), ("Priya", 92), ("Amit", 78)]
students.sort(key=lambda x: x[1], reverse=True)
print(students)  # [('Priya', 92), ('Rahul', 85), ('Amit', 78)]
5

Regular Expressions 🔍

Python
import re

# Find pattern
text = "My phone: 9876543210, email: test@gmail.com"

# Find phone number
phone = re.search(r"\d{10}", text)
print(phone.group())  # 9876543210

# Find email
email = re.search(r"[\w.]+@[\w.]+", text)
print(email.group())  # test@gmail.com

# Find all numbers
nums = re.findall(r"\d+", "I have 3 cats and 5 dogs")
print(nums)  # ['3', '5']

# Validate email
def is_valid_email(email):
    pattern = r'^[\w.]+@[\w]+\.[\w.]+$'
    return bool(re.match(pattern, email))

print(is_valid_email("test@gmail.com"))   # True
print(is_valid_email("invalid@"))         # False

# Replace text
result = re.sub(r"\d+", "***", "Phone: 12345")
print(result)  # Phone: ***
6

APIs & Web Scraping 🌐

🔗 APIs — Fetch Data from the Internet!

Python
# pip install requests
import requests

# GET request — Fetch data
response = requests.get("https://jsonplaceholder.typicode.com/users/1")
if response.status_code == 200:
    data = response.json()
    print(f"Name: {data['name']}")
    print(f"Email: {data['email']}")

# Weather API example (pseudo code)
# api_key = "your_api_key"
# url = f"http://api.openweathermap.org/data/2.5/weather?q=Delhi&appid={api_key}"
# weather = requests.get(url).json()
# print(f"Temp: {weather['main']['temp']}K")

🕷️ Web Scraping — Extract Data from Websites!

Python
# pip install beautifulsoup4
from bs4 import BeautifulSoup
import requests

# Scrape a webpage
url = "https://quotes.toscrape.com/"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")

# Find all quotes
quotes = soup.find_all("span", class_="text")
authors = soup.find_all("small", class_="author")

for quote, author in zip(quotes[:5], authors[:5]):
    print(f'"{quote.text}" — {author.text}')
⚠️
Important: Before scraping, check robots.txt and follow terms of service!
7

Multithreading & Multiprocessing ⚡

Python
import threading
import time

def download_file(filename):
    print(f"⬇️ Downloading {filename}...")
    time.sleep(2)  # Simulate download
    print(f"✅ {filename} downloaded!")

# Without threading — 6 seconds total
# download_file("file1.pdf")
# download_file("file2.pdf")
# download_file("file3.pdf")

# With threading — ~2 seconds total! 🚀
threads = []
for f in ["file1.pdf", "file2.pdf", "file3.pdf"]:
    t = threading.Thread(target=download_file, args=(f,))
    threads.append(t)
    t.start()

for t in threads:
    t.join()
print("All downloads complete! 🎉")
8

Data Science & ML Intro 🤖

📊 NumPy & Pandas Basics

Python
# pip install numpy pandas matplotlib scikit-learn
import numpy as np
import pandas as pd

# NumPy — Fast numerical computing
arr = np.array([1, 2, 3, 4, 5])
print(arr * 2)        # [2, 4, 6, 8, 10]
print(np.mean(arr))   # 3.0
print(np.std(arr))    # 1.414

# Pandas — Data manipulation
data = {
    "Name": ["Rahul", "Priya", "Amit"],
    "Marks": [85, 92, 78],
    "City": ["Delhi", "Mumbai", "Pune"]
}
df = pd.DataFrame(data)
print(df)
print(df.describe())          # Statistics
print(df[df["Marks"] > 80])   # Filter

🤖 Simple ML — Make Predictions!

Python
from sklearn.linear_model import LinearRegression
import numpy as np

# Training data — Study hours vs Marks
hours = np.array([1, 2, 3, 4, 5, 6, 7, 8]).reshape(-1, 1)
marks = np.array([20, 35, 45, 55, 65, 72, 80, 88])

# Train model
model = LinearRegression()
model.fit(hours, marks)

# Predict!
study_hours = 10
predicted_marks = model.predict([[study_hours]])
print(f"📈 {study_hours} hours study → {predicted_marks[0]:.0f} marks predicted!")
# ~100 marks predicted!
🚀
This is just an introduction! Complete learning path for ML: NumPy → Pandas → Matplotlib → Scikit-learn → TensorFlow/PyTorch
💻 Practice Now →