class Book:
def __init__(self, name):
self.name = name
def __repr__(self):
return f"<Book: {self.name}>"
def __eq__(self, other):
if not isinstance(other, type(self)):
return False
return self.name == other.name
class Lib:
def __init__(self, books=None):
if books is None:
self.books = []
else:
self.books = books[:]
def __iadd__(self, other):
if not isinstance(other, Book):
raise TypeError("Not a book")
self.books.append(other)
return self
def __iter__(self):
return iter(self.books)
lib = Lib()
book1 = Book("Fluent Python")
book2 = Book("Mein Kampf")
lib += book1
lib += book2
for book in lib:
print(book)
Однако, лучше не злоупотреблять оверрайдингом операторов неявной логикой и сделать явный метод .add_book() и явный метод .iterate_books()