New instance has old instance attribute values [duplicate]

一笑奈何 提交于 2019-12-11 03:47:48

问题


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?


回答1:


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 []


来源:https://stackoverflow.com/questions/31453008/new-instance-has-old-instance-attribute-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!