5.3 מתודות קסם פתרון
class Book:
def __init__(self, title, author, isbn, quantity):
self.title = title
self.author = author
self.isbn = isbn
self.quantity = quantity
def __str__(self):
return f"Title: {self.title}, Author: {self.author}, ISBN: {self.isbn}, Quantity: {self.quantity}"
def __eq__(self, other):
return self.isbn == other.isbn
def __lt__(self, other):
return self.title < other.title
def __gt__(self, other):
return self.title > other.title
def __add__(self, other):
total_quantity = self.quantity + other.quantity
return Book(self.title, self.author, self.isbn, total_quantity)
# Create instances of Book
book1 = Book("Python Programming", "John Smith", "978-0-13-444432-1", 10)
book2 = Book("Data Structures and Algorithms", "Alice Johnson", "978-0-13-407643-0", 15)
book3 = Book("Python Programming", "John Smith", "978-0-13-444432-1", 5)
# Print book details
print("Book 1:", book1)
print("Book 2:", book2)
# Comparison operations
print("Book 1 == Book 2:", book1 == book2)
print("Book 1 < Book 2:", book1 < book2)
print("Book 1 > Book 2:", book1 > book2)
# Addition operation
combined_book = book1 + book3
print("Combined Book:", combined_book)