Common Python Magic Methods and Their Usage
This article introduces Python's most frequently used magic methods—including __new__, __init__, __str__, __add__, __len__, __getitem__, __setitem__, __delitem__, __contains__, __bool__, __iter__, comparison operators, arithmetic operators, and context manager methods—explaining their purpose, typical use cases, and providing clear code examples for each.
Python provides a set of special "magic" methods that allow developers to customize object behavior for built‑in operations such as creation, representation, arithmetic, comparison, iteration, and context management.
Object creation : class Singleton: _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super().__new__(cls, *args, **kwargs) return cls._instance s1 = Singleton() s2 = Singleton() print(s1 is s2) # True
Initialization : class Person: def __init__(self, name, age): self.name = name self.age = age p = Person("Alice", 30) print(p.name, p.age) # Alice 30
String representation : class Person: def __str__(self): return f"Person(name={self.name}, age={self.age})" p = Person("Alice", 30) print(p) # Person(name=Alice, age=30)
Arithmetic operators (addition shown): class Vector: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): if isinstance(other, Vector): return Vector(self.x + other.x, self.y + other.y) return NotImplemented v1 = Vector(1, 2) v2 = Vector(3, 4) v3 = v1 + v2 print(v3.x, v3.y) # 4 6
Container protocols : methods like __len__ , __getitem__ , __setitem__ , __delitem__ , and __contains__ let objects behave like sequences or mappings, enabling use of len() , indexing, in checks, and deletion.
Boolean and iterable behavior : __bool__ defines truthiness, while __iter__ makes an object iterable in for loops.
Comparison operators : __eq__ , __ne__ , __lt__ , __le__ , __gt__ , and __ge__ allow custom object ordering and equality checks.
Context management : __enter__ and __exit__ let objects be used with with statements to manage resources safely.
By implementing these magic methods, developers can create more Pythonic, expressive, and interoperable classes that integrate seamlessly with the language's core features.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.