Python Magic Methods, Properties, and Iterators
Python provides powerful features that make objects more expressive and flexible. Among these are magic methods, properties, and iterators, which allow developers to customize behavior, control attribute access, and enable iteration in a clean, Pythonic way.
✨ Magic Methods
Magic methods (also called dunder methods because they start and end with double underscores) allow you to define how objects behave with built-in operations.
Initialization and Representation
class Person:
def __init__(self, name):
self.name = name
def __str__(self):
return f"Person named {self.name}"
p = Person("Alice")
print(p) # Person named Alice
__init__: Called when an object is created.__str__: Defines the string representation of the object.
Arithmetic Operators
class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __repr__(self):
return f"Vector({self.x}, {self.y})"
v1 = Vector(2, 3)
v2 = Vector(4, 1)
print(v1 + v2) # Vector(6, 4)
Here, __add__ customizes the + operator.
Comparison Operators
class Student:
def __init__(self, grade):
self.grade = grade
def __eq__(self, other):
return self.grade == other.grade
s1 = Student(90)
s2 = Student(90)
print(s1 == s2) # True
🏛️ Properties
Properties allow controlled access to attributes, enabling encapsulation without changing syntax.
Using @property
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError("Radius cannot be negative")
self._radius = value
@property
def area(self):
import math
return math.pi * self._radius ** 2
c = Circle(5)
print(c.area) # 78.5398...
c.radius = 10
print(c.area) # 314.159...
@property: Defines a getter.@radius.setter: Defines a setter with validation.- Properties make attributes behave like variables but with controlled logic.
🔄 Iterators
Iterators allow objects to be traversed using for loops and other iteration contexts.
Iterator Protocol
- An object is an iterator if it implements:
__iter__(): Returns the iterator object itself.__next__(): Returns the next value or raisesStopIteration.
Example: Custom Iterator
class Countdown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
self.current -= 1
return self.current
for num in Countdown(5):
print(num)
# Output: 4 3 2 1 0
This defines a countdown iterator that decrements until zero.
📊 Comparison Table
| Feature | Purpose | Example |
|---|---|---|
| Magic Methods | Customize object behavior with operators and built-ins | __add__, __eq__, __str__ |
| Properties | Control attribute access with getters/setters | @property, @radius.setter |
| Iterators | Enable iteration over objects | __iter__, __next__ |
📖 Conclusion
Python’s magic methods, properties, and iterators provide powerful ways to make objects more expressive, flexible, and Pythonic. Magic methods let you redefine operators, properties enable controlled attribute access, and iterators allow seamless traversal of custom objects. Together, they form the backbone of writing elegant, object-oriented Python code.
No comments:
Post a Comment