玩弄这个答案中找到的代码,我发现了以下奇怪之处。这是我的类声明,一个完全微不足道的 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>
为什么这些实例似乎共享属性?