如何创建实例属性?

时间:2018-01-26 23:18:03

标签: python

我在理解如何声明对象实例属性方面遇到了一些问题。这是我的代码:

class TestItem(object):
    def __init__(self):
        super(TestItem, self).__init__()

    def import_(self, value):
        self.value = value


class TestItems(object):
    def __init__(self, items=[]):
        super(TestItems, self).__init__()
        self.items = items

    def __getitem__(self, index):
        return self.items[index]

    def __len__(self):
        return len(self.items)

    def import_from_list(self, data):
        for i in data:
            item = TestItem()
            item.import_(i)
            self.items.append(item)


data = []

data.append(TestItems())
data[-1].import_from_list(['A', 'B'])

for i, j in enumerate(data):
    print('Size of data[%i] - %i' % (i, len(j)))

data.append(TestItems())
data[-1].import_from_list([1, 2])

for i, j in enumerate(data):
    print('Size of data[%i] - %i' % (i, len(j)))
    print('First element of data[%i] - %s' % (i, j[0].value))
print(data[0])
print(data[1])

这是输出:

Size of data[0] - 2
Size of data[0] - 4
First element of data[0] - A
Size of data[1] - 4
First element of data[1] - A
<__main__.TestItems object at 0x000002C0765F51D0>
<__main__.TestItems object at 0x000002C0765F52B0>

看起来数组itemsTestsItem的所有实例之间共享,但它不应该。我做错了什么?

UPD:

我这样修好了:

class TestItems(object):
    def __init__(self, items=None):
        super(TestItems, self).__init__()
        self.items = items or []

0 个答案:

没有答案