collections.MutableSequence子类似乎是单例?

时间:2012-05-31 19:47:40

标签: python abc

  

可能重复:
  “Least Astonishment” in Python: The Mutable Default Argument

使用this answer中找到的代码,我发现了以下奇怪之处。这是我的类声明,一个完全无关紧要的MutableSequence子类:

import collections
class DescriptorList(MutableSequence):
    def __init__(self, items=[]):
        super(DescriptorList, self).__init__()
        self.l = items

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

    def __getitem_(self, index):
        return self.l[index]

    def __setitem__(self, index, value):
        self.l[index] = value

    def __delitem__(self, index):
        del self.l[index]

    def insert(self, index, value):
        self.l.insert(index, value)

现在,这是奇怪的:

Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import DescriptorList
>>> b=DescriptorList()
>>> c=DescriptorList
>>> c=DescriptorList()
>>> c.append(5)
>>> b[:]
[5]
>>> b.append(6)
>>> c[:]
[5, 6]
>>> c
<DescriptorList object at 0x100ccfc50>
>>> b
<DescriptorList object at 0x100a32550>

为什么实例会出现共享属性?

0 个答案:

没有答案