新实例具有旧的实例属性值

时间:2015-07-16 11:34:12

标签: python constructor

我想实例化多个图书实例。在我的__init__()方法中,我指定了一些默认值。因此,我希望每次实例化一本新书时,所有旧值都将被我指定为__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,因为我写道:

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

P.S。我知道这里有一个类似的问题,但它是关于类变量的。我认为我的变量不是类变量。我错了吗?

1 个答案:

答案 0 :(得分:0)

您不应使用SELECT t1.device_id, t1.entry_id, t1.data, t1.entry_date FROM some_table as t1 inner join ( select device_id,max(entry_date) as entry_date from some_table group by device_id ) as t2 on t1.device_id=t2.device_id and t1.entry_date=t2.entry_date 作为默认参数。

[]