πŸ”„ 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

  1. What magic methods (dunder methods) are in Python.

  2. How to overload operators (+, -, ==, etc.) in your classes.

  3. How to implement __str__ and __repr__ for readable object representations.

  4. 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

__str__(self)

str(obj) or print(obj)

Human-readable string representation

__repr__(self)

repr(obj)

Developer-friendly representation

__add__(self, other)

obj1 + obj2

Addition operator overloading

__eq__(self, other)

obj1 == obj2

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.y

Using 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

  1. Create a file named vector_practice.py.

  2. Implement the Vector class as shown above.

  3. Add a magic method __sub__(self, other) to subtract vectors.

  4. Add a method magnitude(self) that returns the vector’s length ((x**2 + y**2)**0.5).

  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.0

Expected output:

Vector(3, 4)
Vector(1, 2)
Add: Vector(4, 6)
Sub: Vector(2, 2)
Equal? False
Equal? True
Magnitude v1: 5.0

Run:

python vector_practice.py

Once 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.

Keep Reading