- Create a class Book and initialize it with title, author, and price.
- Create a magic method __eq__, the __eq__ method will check the equality between two objects
- Create a magic method __ge__, the __ge__ method will check >= relationship with another object. (Only comparing the price attribute)
- Create a magic method __lt__, the __lt__ method will check < relationship with another object. (Only comparing the price attribute)
- In all above three magic methods we are comparing two different objects of same class, we need to check / verify here if those objects are from the same class. In all above three magic methods use built-in method isinstance to verify / check if the other object is of same class.
class Book:
def __init__(self, title, author, price):
self.title = title
self.author = author
self.price = price
def __eq__(self, other):
if isinstance(other, Book):
if self.title == other.title and self.author == other.author and self.price == other.price:
return True
else:
return False
else:
raise ValueError
def __ge__(self, other):
if isinstance(other, Book):
if self.price >= other.price:
return True
else:
return False
else:
raise ValueError
def __lt__(self, other):
if isinstance(other, Book):
if self.price < other.price:
return True
else:
return False
else:
raise ValueError
Comments
Leave a comment