← Back to Python

All Topics

Advertisement

Learn/Python/Intermediate Python

Magic Methods

Topic: OOP

Advertisement

Introduction

Magic methods (dunder methods) allow custom behavior for built-in operations.

Comparison Methods

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    def __eq__(self, other):
        return self.x == other.x and self.y == other.y
    
    def __lt__(self, other):
        return (self.x ** 2 + self.y ** 2) < (other.x ** 2 + other.y ** 2)
    
    def __le__(self, other):
        return self == other or self < other

Arithmetic Operators

class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)
    
    def __mul__(self, scalar):
        return Vector(self.x * scalar, self.y * scalar)
    
    def __repr__(self):
        return f"Vector({self.x}, {self.y})"

Container Methods

class Queue:
    def __init__(self):
        self.items = []
    
    def __len__(self):
        return len(self.items)
    
    def __contains__(self, item):
        return item in self.items
    
    def __iter__(self):
        return iter(self.items)

Practice Problems

  1. Implement comparison for fraction class
  2. Create custom list with arithmetic operations
  3. Add len and bool to a class
  4. Implement call to make object callable
  5. Create a string representation for debugging

Advertisement

Advertisement

Need More Practice?

Get personalized Python help from ChatWhole's AI-powered platform.

Get Expert Help →