Monday, 3 November 2025

#21a Dunder Method - Samples

Python Dunder (Magic) Methods – Complete Guide with Demos

Python Dunder (Magic) Methods – Complete Guide with Demos

Click Run to execute examples or Copy to copy code. Works directly inside Blogger.

Click here for Key characteristics of DUNDER (DOUBLE Under Score ___) methods:

Dunder methods, also known as magic methods or special methods, are a core feature in Python that allow classes to interact with the language's built-in functions and operators. The term "dunder" is a contraction of "double underscore," referring to the fact that these methods are named with double underscores at both the beginning and end (e.g., __init__, __add__, __str__).

Implicit Invocation: Dunder methods are typically not called directly by the programmer. Instead, they are implicitly invoked by the Python interpreter in response to specific actions or operations. For example, when you use the + operator on two objects, Python implicitly calls the __add__ dunder method of the first object.

Operator Overloading: Dunder methods enable operator overloading, allowing you to define custom behavior for operators (like +, -, *, ==, []) when applied to instances of your classes. This makes your custom objects behave more like native Python types. Integration with Built-in Functions: Many built-in Python functions (such as len(), str(), int()) rely on corresponding dunder methods (__len__, __str__, __int__) to determine how they should interact with instances of your classes.

Customizing Class Behavior: Dunder methods allow you to customize various aspects of your class's behavior,

including object initialization (__init__), object representation (__str__, __repr__), attribute access (__getattr__, __setattr__), and iteration (__iter__, __next__).

Examples of common dunder methods:

  • __init__: Called when a new instance of a class is created, used for initialization.
  • __str__: Defines the informal string representation of an object (what print() shows).
  • __repr__: Defines the official string representation of an object, often used for debugging.
  • __add__, __sub__, __mul__: Define behavior for arithmetic operations.
  • __len__: Defines the behavior of the len() function for an object.
  • __getitem__, __setitem__: Define behavior for indexing and slicing (e.g., obj[key]).

By implementing dunder methods in your classes, you can create more robust, intuitive, and "Pythonic" custom objects that seamlessly integrate with the language's features.

__init__ – Initialize instance attributes

class Person:
    def __init__(self, name):
        self.name = name
        print("Hello", self.name)

Person("Alice")

__repr__ – Developer representation

class Point:
    def __init__(self, x, y): self.x, self.y = x, y
    def __repr__(self): return f"Point({self.x},{self.y})"

p = Point(2,3)
print(repr(p))

__str__ – User-friendly string

class Point:
    def __init__(self, x, y): self.x, self.y = x, y
    def __str__(self): return f"({self.x},{self.y})"

print(Point(1,4))

__add__ – Add two objects

class Vec:
    def __init__(self, x, y): self.x, self.y = x, y
    def __add__(self, o): return Vec(self.x + o.x, self.y + o.y)
    def __repr__(self): return f"Vec({self.x},{self.y})"

print(Vec(1,2)+Vec(3,4))

__len__ – Object length

class L:
    def __init__(self, data): self.data = data
    def __len__(self): return len(self.data)

print(len(L([1,2,3])))

__getitem__ – Index access

class Seq:
    def __init__(self): self.data = [10,20,30]
    def __getitem__(self, k): return self.data[k]

s = Seq()
print(s[1])

__call__ – Make instance callable

class Adder:
    def __init__(self, n): self.n = n
    def __call__(self, x): return x + self.n

add5 = Adder(5)
print(add5(10))

__enter__ / __exit__ – Context manager

class Ctx:
    def __enter__(self): print("enter"); return self
    def __exit__(self,exc,val,tb): print("exit")

with Ctx(): print("inside")

__bool__ – Truth value

class C:
    def __init__(self, items): self.items = items
    def __bool__(self): return len(self.items) > 0

print(bool(C([])), bool(C([1])))

__hash__ – Hashable object

class H:
    def __init__(self,v): self.v=v
    def __hash__(self): return hash(self.v)

print({H(5): 'ok'})
© Python Dunder Methods Demo | Works inside Blogger | Built with Pyodide Runtime

#21 Python Dunder Methods - Magic Feature

Complete Python Dunder Methods — Interactive Guide

Complete Python Dunder Methods — Interactive Guide

All common dunder (magic) methods are listed below. Each method has: โ„น️ info (hover/tap), a code snippet, Copy, Run, and a collapsible output panel. The examples are minimal demonstrations so you can run them safely in the browser using Pyodide.

Index — Click to jump

Sunday, 2 November 2025

#20b Python (run+edit in browser ^ all in one)

๐Ÿ Python Basics — 5 Interactive Modules

Edit code live with syntax highlighting and click ▶ Run. Each module runs separately via Pyodide.

Module 1 — Hello & Print

Your first Python program using print() and input().
๐Ÿ’ฌ Show Output
— output here —

Module 2 — Variables & Types

Numbers, strings, booleans, and type checking.
๐Ÿ’ฌ Show Output
— output here —

Module 3 — Control Flow

Using if/else, loops, and range().
๐Ÿ’ฌ Show Output
— output here —

Module 4 — Functions & Modules

Defining functions and using the math library.
๐Ÿ’ฌ Show Output
— output here —

Module 5 — Lists & Comprehensions

Creating lists, slicing, and list comprehensions.
๐Ÿ’ฌ Show Output
— output here —

#20a Python Run

๐Ÿ Python Basics — 5 Interactive Modules

Each module runs separately via Pyodide. Output appears right below the code. Colored console output: ๐ŸŸข stdout / ๐Ÿ”ด stderr / ๐ŸŸฃ status

Module 1 — Hello & Print

Your first Python program — using print() and input().
# Module 1 — Hello & print
name = input("What's your name? ")
print(f"Hello, {name}! Welcome to Python basics.")
— output here —

Module 2 — Variables & Types

Numbers, strings, booleans, and type checking.
x = 42
y = 3.14
name = "Ada"
is_ready = True

print(x, type(x))
print(y, type(y))
print(name.upper(), type(name))
print("Is ready?", is_ready)
— output here —

Module 3 — Control Flow

Using if/else, loops, and range().
n = 5
for i in range(1, n+1):
    if i % 2 == 0:
        print(i, "is even")
    else:
        print(i, "is odd")

count = 3
while count > 0:
    print("Counting down:", count)
    count -= 1
— output here —

Module 4 — Functions & Modules

Defining functions and using Python's standard library.
import math

def circle_area(radius):
    return math.pi * radius ** 2

r = 2.5
print(f"Area of circle with radius {r} is {circle_area(r):.3f}")
— output here —

Module 5 — Lists & Comprehensions

Creating lists, slicing, and list comprehensions.
numbers = [1, 2, 3, 4, 5]
squares = [n**2 for n in numbers]
evens = [n for n in numbers if n % 2 == 0]
print("numbers:", numbers)
print("squares:", squares)
print("evens:", evens)
print("first two:", numbers[:2])
— output here —

#20 Python Revisit ( + In Browser Python Run)

Python basics — 5 modules (interactive)

Syntax highlighting via Prism.js. In-browser execution via Pyodide. Colored console output: ๐ŸŸข stdout / ๐Ÿ”ด stderr / ๐ŸŸฃ status.

Interactive runner

Paste examples into the editor (or use Copy & Use from any module) and click Run. Output appears below.
Editor
Pyodide status: loading...
Quick snippets
Console output
— ready —

Module 1 — Hello & print

The first program: printing to console, comments, and basic I/O.
# Module 1 — Hello & print
name = input("What's your name? ")
print(f"Hello, {name}! Welcome to Python basics.")

Module 2 — Variables & Types

Numbers, strings, booleans, and type checking.
x = 42
y = 3.14
name = "Ada"
is_ready = True

print(x, type(x))
print(y, type(y))
print(name.upper(), type(name))
print("Is ready?", is_ready)

Module 3 — Control Flow

if/else, for loops, while loops, and range.
n = 5
for i in range(1, n+1):
    if i % 2 == 0:
        print(i, "is even")
    else:
        print(i, "is odd")

count = 3
while count > 0:
    print("Counting down:", count)
    count -= 1

Module 4 — Functions & Modules

Defining functions, parameters, return values, and importing a module.
import math

def circle_area(radius):
    return math.pi * radius ** 2

r = 2.5
print(f"Area of circle with radius {r} is {circle_area(r):.3f}")

Module 5 — Lists & Comprehensions

Creating lists, indexing, slicing, and list comprehensions.
numbers = [1, 2, 3, 4, 5]
squares = [n**2 for n in numbers]
evens = [n for n in numbers if n % 2 == 0]
print("numbers:", numbers)
print("squares:", squares)
print("evens:", evens)
print("first two:", numbers[:2])

Wednesday, 22 October 2025

#19 Web site Demo

Python Website Demo: Full Tutorial (Login, Projects, Customers, Stories)

Python Website Demo Tutorial

Build a complete demo web application using Python + Flask, featuring: login, projects, customers, and success stories pages. Each module gets you closer to a real-world site!

Module 1: Setup & Install Flask

pip install flask flask-login
mkdir pywebdemo
cd pywebdemo
touch app.py
mkdir templates static

Module 2: Base Flask App & Page Routing

# app.py
from flask import Flask, render_template, redirect, url_for
app = Flask(__name__)

@app.route('/')
def home():
    return render_template('home.html')

@app.route('/projects')
def projects():
    return render_template('projects.html')

@app.route('/customers')
def customers():
    return render_template('customers.html')

@app.route('/stories')
def stories():
    return render_template('stories.html')

if __name__ == '__main__':
    app.run(debug=True)

Module 3: Basic Page Templates

<!-- templates/home.html -->
<h1>Welcome to Demo Company</h1>
<a href="/login">Login</a> | <a href="/projects">Projects</a> | <a href="/customers">Customers</a> | <a href="/stories">Success Stories</a>
<!-- templates/projects.html -->
<h2>Our Projects</h2>
<ul>
  <li>Project A: AI Web Platform</li>
  <li>Project B: Mobile Solution</li>
</ul>
<!-- templates/customers.html -->
<h2>Our Customers</h2>
<ul>
  <li>Customer Alpha</li>
  <li>Customer Beta</li>
</ul>
<!-- templates/stories.html -->
<h2>Success Stories</h2>
<p>Customer Alpha tripled sales with our platform!</p>
<p>Customer Beta expanded globally with our mobile tech.</p>

Module 4: Login Page & User System

# app.py (add)
from flask import request, flash
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user

app.secret_key = 'REPLACE_WITH_A_SECRET_KEY'
login_manager = LoginManager()
login_manager.init_app(app)

# Simple Fake User
class User(UserMixin):
    def __init__(self, id):
        self.id = id

@login_manager.user_loader
def load_user(user_id):
    return User(user_id)
# app.py (add route)
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        if request.form['username'] == 'admin' and request.form['password'] == 'password':
            user = User('admin')
            login_user(user)
            return redirect(url_for('home'))
        else:
            flash('Bad credentials!')
    return render_template('login.html')
<!-- templates/login.html -->
<form method="POST">
  <label>Username:</label>
  <input name="username" type="text"><br>
  <label>Password:</label>
  <input name="password" type="password"><br>
  <button type="submit">Login</button>
</form>
{% with messages = get_flashed_messages() %}
  {% if messages %}
    <p style="color:red;">{{ messages[0] }}</p>
  {% endif %}
{% endwith %}
# app.py (add route)
@app.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('home'))

Module 5: Protected Pages and Navigation

# app.py (protect routes)
@app.route('/admin')
@login_required
def admin():
    return "

Admin Only Page

"

Module 6: Basic Styling and Navigation Bar

<!-- templates/base.html -->
<nav>
  <a href="/">Home</a> | 
  <a href="/projects">Projects</a> | 
  <a href="/customers">Customers</a> | 
  <a href="/stories">Success Stories</a> | 
  {% if current_user.is_authenticated %}
    <a href="/logout">Logout</a>
  {% else %}
    <a href="/login">Login</a>
  {% endif %}
</nav>
<hr>
{% block content %}{% endblock %}
<!-- Usage: in your pages -->
{% extends "base.html" %}
{% block content %}
  ...page content...
{% endblock %}
/* static/style.css */
body { font-family: Arial, sans-serif; background: #f7faff; }
nav { font-size: 1.2em; margin-bottom: 12px; }
a { color: #00adb5; text-decoration: none; margin-right: 10px; }
hr { margin-bottom: 30px; }

Module 7: Adding Fake Data for Projects & Customers

# app.py
projects_data = [
  {"title": "AI Web Platform", "desc": "Cutting-edge machine learning project."},
  {"title": "Mobile Solution", "desc": "Cross-platform mobile app."}
]
customers_data = ["Customer Alpha", "Customer Beta"]

@app.route('/projects')
def projects():
    return render_template('projects.html', projects=projects_data)

@app.route('/customers')
def customers():
    return render_template('customers.html', customers=customers_data)
{% extends "base.html" %}
{% block content %}
  <h2>Our Projects</h2>
  <ul>
    {% for p in projects %}
      <li><b>{{ p.title }}</b> — {{ p.desc }}</li>
    {% endfor %}
  </ul>
{% endblock %}

Module 8: Success Stories Dynamic Content

# app.py
stories_data = [
  {"customer": "Alpha", "story": "Tripled sales!"},
  {"customer": "Beta", "story": "Expanded globally!"}
]

@app.route('/stories')
def stories():
    return render_template('stories.html', stories=stories_data)
{% extends "base.html" %}
{% block content %}
  <h2>Success Stories</h2>
  <ul>
    {% for s in stories %}
      <li><b>{{ s.customer }}:</b> {{ s.story }}</li>
    {% endfor %}
  </ul>
{% endblock %}

Module 9: Flash Messages & User Feedback

# On login fail (see login above)
flash('Bad credentials!')
{% with messages = get_flashed_messages() %}
  {% if messages %}
    <div style="color:red;">
    {% for message in messages %}
      {{ message }}<br>
    {% endfor %}
    </div>
  {% endif %}
{% endwith %}

Module 10: Finalizing & Running Your Demo Website

export FLASK_APP=app.py
flask run
  1. Visit http://127.0.0.1:5000/ in your browser.
  2. Login using admin / password (demo only).
  3. Explore projects, customers, and stories pages.
  4. You can expand with databases, forms, and REST APIs later!
This boilerplate gives you a fast way to try out and demo a real Python-based web application!

#18 gmail AUthentication

Gmail Authentication with Django: Step-by-Step Tutorial

Gmail Authentication in Django: Step-by-Step Tutorial

Learn how to set up Gmail (Google) authentication on your Django site using the popular third-party package django-allauth. This method lets users log in or sign up with their Google account in a secure, scalable way.

Step 1: Install Required Packages

pip install django-allauth

Step 2: Add Apps and Settings in settings.py

INSTALLED_APPS = [
    # Django default apps...
    "django.contrib.sites",
    "allauth",
    "allauth.account",
    "allauth.socialaccount",
    "allauth.socialaccount.providers.google",
]

SITE_ID = 1

AUTHENTICATION_BACKENDS = [
    "django.contrib.auth.backends.ModelBackend",
    "allauth.account.auth_backends.AuthenticationBackend",
]

LOGIN_REDIRECT_URL = "/"

Step 3: Add Allauth URLs to Project

# mysite/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path("admin/", admin.site.urls),
    path("accounts/", include("allauth.urls")),
]

Step 4: Create a Google OAuth App

  • Go to Google Cloud Console > APIs & Services > Credentials
  • Create a new OAuth Client ID (Web application)
  • Add authorized redirect URI: http://localhost:8000/accounts/google/login/callback/
  • Save your Client ID and Secret.

Step 5: Configure Google Provider in Django Admin

  1. Run the server and log in to /admin
  2. Find Sites and make sure domain is localhost
  3. Find Social applications and add Google:
    • Provider: Google
    • Name: Google
    • Client ID: (your Google client ID)
    • Secret Key: (your Google secret)
    • Sites: Select your current site

Step 6: Customizing Login Button in Template

<a href="{% provider_login_url 'google' %}">
  Login with Google
</a>

Step 7: Try It Out!

  • Visit /accounts/login/ and click Login with Google
  • Authenticate with your Gmail account
  • Get redirected to your app, now signed in!

Extra: Customizing Forms, User Model, and Redirects

  • Override templates in templates/account/
  • Extend user model for extra fields if needed
  • Change LOGIN_REDIRECT_URL for custom flows
With django-allauth, you can add many other social providers easily (Facebook, Twitter, etc).

#21a Dunder Method - Samples

Python Dunder (Magic) Methods – Complete Guide with Demos Python Dunder (Magic) Methods – Complete Guide with Demos ...