classBook: def __init__(self, title, author, pages): self.title = title self.author = author self.pages = pages def __str__(self): # 用户友好字符串,被 print() 和 str() 调用 return f"《{self.title}》 - {self.author}" def __repr__(self): # 开发者/解释器友好字符串,用于调试 return f"Book('{self.title}', '{self.author}', {self.pages})" def __len__(self): # 定义对象的“长度”,被 len() 调用 return self.pages def __eq__(self, other): # 定义相等性比较 (==) if isinstance(other, Book): return self.title == other.title and self.author == other.author return False def __add__(self, other): # 定义加法行为 (+) if isinstance(other, Book): new_title = f"{self.title} & {other.title}" new_author = f"{self.author} 和 {other.author}" new_pages = self.pages + other.pages return Book(new_title, new_author, new_pages) raise TypeError("只能与Book对象相加")book1 = Book("Python编程", "小明", 300)book2 = Book("算法导论", "小红", 500)print(book1) # 输出: 《Python编程》 - 小明 (调用 __str__)print(repr(book1)) # 输出: Book('Python编程', '小明', 300) (调用 __repr__)print(len(book1)) # 输出: 300 (调用 __len__)print(book1 == book2) # 输出: False (调用 __eq__)book3 = book1 + book2 # 调用 __add__print(book3.title) # 输出: Python编程 & 算法导论