Operator Overloading

Operator Overloading in Python with Simple Examples

Operator overloading allows you to define how Python operators (like +-*, etc.) work with your custom classes. This makes your objects behave more like built-in types.


1. What is Operator Overloading?

  • Python operators have predefined behaviors for built-in types.
  • Operator overloading lets you redefine these behaviors for your custom classes.
  • Achieved using special methods (dunder methods) like __add____sub__, etc.

2. Basic Syntax

python

class ClassName:
    def __special_method__(self, other):
        # Define custom behavior

3. Common Operator Overloading Methods

OperatorMethodExample Usage
+__add__obj1 + obj2
-__sub__obj1 - obj2
*__mul__obj1 * obj2
/__truediv__obj1 / obj2
==__eq__obj1 == obj2
<__lt__obj1 < obj2
>__gt__obj1 > obj2
str()__str__print(obj)

4. Practical Examples

Example 1: Vector Addition

python

class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    # Overload + operator
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)
    
    # Overload string representation
    def __str__(self):
        return f"Vector({self.x}, {self.y})"

# Usage
v1 = Vector(2, 3)
v2 = Vector(1, 4)
result = v1 + v2  # Calls v1.__add__(v2)
print(result)  # Output: Vector(3, 7)

Example 2: Book Comparison

python

class Book:
    def __init__(self, title, pages):
        self.title = title
        self.pages = pages
    
    # Overload > operator
    def __gt__(self, other):
        return self.pages > other.pages
    
    # Overload == operator
    def __eq__(self, other):
        return self.pages == other.pages
    
    def __str__(self):
        return f"'{self.title}' ({self.pages} pages)"

# Usage
book1 = Book("Python Basics", 300)
book2 = Book("Advanced Python", 500)

print(book1 > book2)   # Output: False
print(book1 == book2)  # Output: False
print(f"Book 1: {book1}")  # Output: Book 1: 'Python Basics' (300 pages)

Example 3: Shopping Cart Total

python

class ShoppingCart:
    def __init__(self):
        self.items = []
        self.prices = []
    
    def add_item(self, item, price):
        self.items.append(item)
        self.prices.append(price)
    
    # Overload + operator to combine carts
    def __add__(self, other):
        new_cart = ShoppingCart()
        new_cart.items = self.items + other.items
        new_cart.prices = self.prices + other.prices
        return new_cart
    
    # Overload string representation
    def __str__(self):
        return f"Cart: {self.items} - Total: ${sum(self.prices)}"

# Usage
cart1 = ShoppingCart()
cart1.add_item("Apple", 1.5)
cart1.add_item("Banana", 0.8)

cart2 = ShoppingCart()
cart2.add_item("Milk", 2.5)

combined_cart = cart1 + cart2  # Calls cart1.__add__(cart2)
print(combined_cart)
# Output: Cart: ['Apple', 'Banana', 'Milk'] - Total: $4.8

Example 4: Student Grade Comparison

python

class Student:
    def __init__(self, name, grade):
        self.name = name
        self.grade = grade
    
    # Overload < operator
    def __lt__(self, other):
        return self.grade < other.grade
    
    # Overload string for printing
    def __str__(self):
        return f"{self.name}: {self.grade}%"

# Usage
student1 = Student("Alice", 85)
student2 = Student("Bob", 92)

print(student1 < student2)  # Output: True
print(student1)  # Output: Alice: 85%
print(student2)  # Output: Bob: 92%

5. Key Benefits of Operator Overloading

  1. Intuitive Code: Makes custom objects work like built-in types.
  2. Readabilityvector1 + vector2 is clearer than vector1.add(vector2).
  3. Consistency: Your classes behave similarly to Python’s built-in classes.

6. Important Notes

  • Don’t Overuse: Only overload operators when it makes logical sense.
  • Consistency: Ensure overloaded operators behave as users would expect.
  • Error Handling: Handle cases where operations might not make sense.

Summary

Operator overloading makes your custom classes more Pythonic and user-friendly. By implementing special methods like __add____eq__, and __str__, you can make your objects work seamlessly with Python’s built-in operators! 🚀

Similar Posts

  • Indexing and Slicing in Python Lists Read

    Indexing and Slicing in Python Lists Read Indexing and slicing are fundamental operations to access and extract elements from a list in Python. 1. Indexing (Accessing Single Elements) Example 1: Basic Indexing python fruits = [“apple”, “banana”, “cherry”, “date”, “fig”] # Positive indexing print(fruits[0]) # “apple” (1st element) print(fruits[2]) # “cherry” (3rd element) # Negative indexing print(fruits[-1]) # “fig”…

  • Curly Braces {} ,Pipe (|) Metacharacters

    Curly Braces {} in Python Regex Curly braces {} are used to specify exact quantity of the preceding character or group. They define how many times something should appear. Basic Syntax: Example 1: Exact Number of Digits python import re text = “Zip codes: 12345, 9876, 123, 123456, 90210″ # Match exactly 5 digits pattern = r”\d{5}” # Exactly…

  • Functions Returning Functions

    Understanding Functions Returning Functions In Python, functions can return other functions, which is a powerful feature of functional programming. Basic Example python def outer(): def inner(): print(“Welcome!”) return inner # Return the inner function (without calling it) # Calling outer() returns the inner function f = outer() # f now refers to the inner function…

  • replace(), join(), split(), rsplit(), and splitlines() methods in Python

    1. replace() Method Purpose: Replaces occurrences of a substring with another substring.Syntax: python string.replace(old, new[, count]) Examples: Example 1: Basic Replacement python text = “Hello World” new_text = text.replace(“World”, “Python”) print(new_text) # Output: “Hello Python” Example 2: Limiting Replacements (count) python text = “apple apple apple” new_text = text.replace(“apple”, “orange”, 2) print(new_text) # Output: “orange orange apple”…

  • Basic Character Classes

    Basic Character Classes Pattern Description Example Matches [abc] Matches any single character in the brackets a, b, or c [^abc] Matches any single character NOT in the brackets d, 1, ! (not a, b, or c) [a-z] Matches any character in the range a to z a, b, c, …, z [A-Z] Matches any character in the range A to Z A, B, C, …, Z [0-9] Matches…

  • Generators in Python

    Generators in Python What is a Generator? A generator is a special type of iterator that allows you to iterate over a sequence of values without storing them all in memory at once. Generators generate values on-the-fly (lazy evaluation) using the yield keyword. Key Characteristics Basic Syntax python def generator_function(): yield value1 yield value2 yield value3 Simple Examples Example…

Leave a Reply

Your email address will not be published. Required fields are marked *