Answer to Question #307592 in Python for dv13

Question #307592

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


1
Expert's answer
2022-03-08T07:12:10-0500
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

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS