新实例具有旧实例属性值 [英] New instance has old instance attribute values
问题描述
我想实例化书籍的多个实例。在我的 __ init __()
方法中,指定一些默认值。因此,我希望每次实例化一本新书时,所有旧值都将替换为我为 __ init __()
的参数指定的默认值。
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__()
.
相反,我明白了:
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!
为什么 foo.book_rows [0] .sent
还在吗?自从我写道:我的 __ init __()
方法不是应该擦除所有 book_rows
的方法,
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 = [])
?
PS我知道有一个类似的问题,但这是关于类变量的。我认为这里的变量不是类变量。我错了吗?
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?
推荐答案
您不应默认使用 []
class Book(object):
def __init__(self, title=None, book_rows=None):
self.title = title
self.book_rows = book_rows or []
这篇关于新实例具有旧实例属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!