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

#21a Dunder Method - Samples

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