Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New instance has old instance attribute values [duplicate]

I want to instantiate multiple instances of books. In my __init__() method I specify some default values. So I am expecting that every time I instantiate a new book, all the old values will be replaced by the default ones I specified as arguments for __init__().

On the contrary, I get this:

class Book(object):
    def __init__(self, title=None, book_rows=[]):
        self.title = title
        self.book_rows = book_rows
    def add_line(self, book_row):
        assert type(book_row) == BookLine
        self.book_rows.append(book_row)

class BookLine(object):
    def __init__(self, sent):
        self.sent = sent

foo = Book(title='First book')
book_row = BookLine(sent='This is a sentence')
foo.add_line(book_row)

foo.title
# 'First book'
foo.book_rows[0].sent
# 'This is a sentence'

foo = Book(title='Second book. This should be new')
foo.title
# 'Second book. This should be new' <-- OK

foo.book_rows[0].sent
# 'This is a sentence' <-- WRONG!

Why is foo.book_rows[0].sent still there? Isn't my __init__() method supposed to wipe all the book_rows, since I wrote:

__init__(self, title=None, book_rows=[])

?

P.S. I know there's a similar question, but it was about class variables. I think that my variables here are not class variables. Am I wrong?

like image 594
Kurt Bourbaki Avatar asked Apr 26 '26 23:04

Kurt Bourbaki


1 Answers

You should not use [] as default argument.

class Book(object):
    def __init__(self, title=None, book_rows=None):
        self.title = title
        self.book_rows = book_rows or []
like image 60
lukkol Avatar answered Apr 29 '26 13:04

lukkol