Dunder_Methods_or_Magic_Functions
Dunder_Methods_or_Magic_Functions
Functions
python
Copy
# Every class implicitly inherits from object
class MyClass:# This is equivalent to class MyClass(objec
t):
pass
__init__(self)
Constructor method called when creating an object
__str__(self)
Defines string representation of the object
python
Copy
def __str__(self):
return f"Student: {self.name}, Age: {self.age}"
__repr__(self)
Provides a detailed string representation
python
Copy
def __repr__(self):
return f"Student(name='{self.name}', age={self.age})"
__eq__(self, other)
Defines equality comparison ( == )
__lt__(self, other)
Defines less than comparison ( < )
python
Copy
def __lt__(self, other):
return self.age < other.age
__len__(self)
Returns the length of the object
python
Copy
def __len__(self):
return len(self.attributes)# Example
__getitem__(self, key)
Allows indexing or key-based access
4. Context Management
python
Copy
class FileManager:
def __init__(self, filename):
self.filename = filename
def __enter__(self):
self.file = open(self.filename, 'r')
return self.file
Best Practices
1. Implement magic methods to make your classes more Pythonic
Complete Example
def __str__(self):
return f"Library: {self.name}"
def __len__(self):
return len(self.books)
Summary
Magic functions provide special behaviors to classes
With Python 2.0 (released in 2000), the protocol for special methods
became more formalized
Key milestone: Python 2.2 introduced the concept of "new-style classes" which
significantly expanded and standardized the use of special methods (dunder
methods).
python
Copy
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
python
Copy
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
__del__
Called when object is about to be destroyed
python
Copy
class FileHandler:
def __del__(self):
print("Object is being deleted")
self.close_resources()
String Representation
__str__
User-friendly string representation
python
Copy
class Point:
def __str__(self):
return f"Point(x={self.x}, y={self.y})"
__repr__
python
Copy
class Point:
def __repr__(self):
return f"Point({self.x}, {self.y})"
Comparison Methods
Comparison Magic Methods
__lt__ : Less than <
__eq__ : Equal ==
python
Copy
class Product:
def __init__(self, price):
self.price = price
__getitem__
Enables indexing
python
Copy
class CustomDict:
def __getitem__(self, key):
return self.data[key]
python
Copy
class CountDown:
def __iter__(self):
self.n = 5
return self
def __next__(self):
if self.n > 0:
result = self.n
self.n -= 1
return result
raise StopIteration
__sub__ : Subtraction
__mul__ : Multiplication
__truediv__ : Division /
python
Copy
class Vector:
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
python
Copy
def __radd__(self, other):
return self + other# Fallback implementation
Context Management
__enter__ and __exit__
Used with with statement
python
Copy
class DatabaseConnection:
def __enter__(self):
self.connect()
python
Copy
def __bool__(self):
return len(self.data) > 0
Numeric Methods
__abs__ : Absolute value
__round__ : Rounding
python
Copy
def __abs__(self):
return math.sqrt(self.x**2 + self.y**2)
Advanced Methods
Attribute Handling
__getattr__ : Called for missing attributes
python
Copy
def __getattr__(self, name):
return f"Attribute {name} not found"
Asynchronous Methods
Async Context and Iteration
__await__ : Make object awaitable
python
Copy
async def __aiter__(self):
# Async iteration implementation
pass
python
Copy
def __copy__(self):
return self.__class__(**self.__dict__)
python
Copy
class Multiplier:
def __call__(self, x):
return x * self.factor
python
Copy
class Point:
__slots__ = ['x', 'y']