π Quick Recap (Day 12)
You used inheritance to extend classes and
super()to call parent constructors.You practiced polymorphism by overriding methods in subclasses and iterating over different object types.
π― What Youβll Learn Today
What magic methods (dunder methods) are in Python.
How to overload operators (
+,-,==, etc.) in your classes.How to implement
__str__and__repr__for readable object representations.Why these methods make your custom types feel like native Python types.
π Overview: Magic Methods
Magic methods have names surrounded by double underscores (__init__, __str__). Python uses them to implement built-in behaviors. By defining them, you tell Python how your objects should work with operators and functions.
Common Magic Methods
Method | Called By | Purpose |
|---|---|---|
|
| Human-readable string representation |
|
| Developer-friendly representation |
|
| Addition operator overloading |
|
| Equality comparison |
π Example: A Vector Class
Define a simple 2D Vector class that supports addition, equality checks, and readable printing.
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"Vector({self.x}, {self.y})"
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __eq__(self, other):
return self.x == other.x and self.y == other.yUsing the Vector Class
v1 = Vector(2, 3)
v2 = Vector(4, 5)
print(v1) # Vector(2, 3)
print(v1 + v2) # Vector(6, 8)
print(v1 == v2) # False
print(v1 == Vector(2, 3)) # Trueπ§ββοΈ Take the Wand and Try Yourself
Create a file named
vector_practice.py.Implement the Vector class as shown above.
Add a magic method
__sub__(self, other)to subtract vectors.Add a method
magnitude(self)that returns the vectorβs length ((x**2 + y**2)**0.5).Instantiate two vectors and demonstrate:
Addition (
+)Subtraction (
-)Equality comparison (
==)Printing (
print()) and magnitude calculation.
Solution Example (vector_practice.py):
# vector_practice.py
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"Vector({self.x}, {self.y})"
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y)
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def magnitude(self):
return (self.x**2 + self.y**2)**0.5
# Practice
v1 = Vector(3, 4)
v2 = Vector(1, 2)
print(v1) # Vector(3, 4)
print(v2) # Vector(1, 2)
print("Add:", v1 + v2) # Vector(4, 6)
print("Sub:", v1 - v2) # Vector(2, 2)
print("Equal?", v1 == v2) # False
print("Equal?", v1 == Vector(3, 4)) # True
print("Magnitude v1:", v1.magnitude()) # 5.0Expected output:
Vector(3, 4)
Vector(1, 2)
Add: Vector(4, 6)
Sub: Vector(2, 2)
Equal? False
Equal? True
Magnitude v1: 5.0Run:
python vector_practice.pyOnce you see these results, youβve mastered magic methods and operator overloading!
Up next: Day 14: Encapsulation & Decorators β learn how to protect and extend your class attributes.