N
N
NakedFace2016-04-17 23:58:49
Python
NakedFace, 2016-04-17 23:58:49

How to correctly overload the += operator when working with class instances in Python?

Hello.
There is a Library class and a Book class.
The program needs to work like this:
lib = Library(1, '51 Some str., NY')
lib += Book('Leo Tolstoi', 'War and Peace')
Created an array books in the Library class to store books, overloaded the operator + = to add objects to this array. But after calling the operator, access to this variable is lost (gives an error on lib.books). Although there is call access.
Here is the program code:

class Book(object):
    def __init__(self, name, author):
        if name == "":
            raise "Book name mustn't be empty"
        self._name = name
        self._autor = author
        self._code = 0

    @property
    def name(self):
        return self._name

    @property
    def autor(self):
        return self._autor

    def tag(self):
        return [word for word in self._name.split(' ') if word[:1].isupper()]

    def __iter__(self):
        yield [self._code, self._name, self._autor]

    def __str__(self):
        return "[{0}] {1} {2}".format(self._code, self._autor, self._name)

class Library(object):
    def __init__(self, address, number):
        self._address = address
        self._number = number
        self._books = []

    @property
    def address(self):
        return self._address

    @property
    def number(self):
        return self._number

    @property
    def books(self):
        return self._books

    def __iadd__(self, book):
        self._books.append(book)
        # print(book.tag())

    def __iter__(self):
        yield self._books

And main.py:
from book import Book
from library import Library

book = Book('War and Peace', 'Tolstoi')
lib = Library(1, '51 Some str., NY')

print(book.name)
print(book.autor)
print(book.tag())
print(book)

print(lib.books) # => []
lib += book
print(lib.books) # => AttributeError: 'NoneType' object has no attribute 'books'

Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
NakedFace, 2016-04-18
@NakedFace

You need to add return self to the overload.

def __iadd__(self, book):
        self._books.append(book)
        return self

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question