Python: Operator Overloading

print(10 + 20)
print(50 - 20)

result = int.__add__(10, 20)

print(result)

result = int.__sub__(50, 20)

print(result)
Python

Output:

30
30

30

30
Plaintext
class Product:
    def __init__(self, name, price, category):
        self.name = name
        self.price = price
        self.category = category
        
    def printDetails(self):
        print("Name:", self.name)
        print("Price:", self.price)
        print("Category", self.category)
        
    def __eq__(self, oth):
        return self.category == oth.category and self.price == oth.price
    
    def __gt__(self, oth):
        return self.category > oth.category and self.price > oth.price
    
    def __ge__(self, oth):
        return self.category >= oth.category and self.price >= oth.price
    
    def __lt__(self, oth):
        return self.category < oth.category and self.price < oth.price
    
    def __le__(self, oth):
        return self.category <= oth.category and self.price <= oth.price
        
    def __str__(self):
        return f"Name: {self.name}, Category: {self.category}, Price: {self.price}"

    def __repr__(self):
        return f"Product(name={self.name}, price={self.price}, category={self.category})"
        
        
my_product1 = Product("Sonic Wireless SWH-30G21", 99.99, "Headphone")
my_product2 = Product("SmartHome Hub X200", 199, "Smart Home")
my_product3 = Product("Aqua Pro X500", 99.99, "Headphone")


print(my_product1 == my_product3)
print(my_product1 == my_product2)
print(my_product1 >= my_product3)
print(my_product2 < my_product3)

print(my_product1)
print(str(my_product1))

print(repr(my_product1))
Python

Output:

True
False
True
False

Name: Sonic Wireless SWH-30G21, Category: Headphone, Price: 99.99
Name: Sonic Wireless SWH-30G21, Category: Headphone, Price: 99.99

Product(name=Sonic Wireless SWH-30G21, price=99.99, category=Headphone)
Plaintext

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.