(我使用的是 python 2.7)python 文档表明您可以将映射传递给内置的 dict,它将将该映射复制到新的 dict 中:
http://docs.python.org/library/stdtypes.html#mapping-types-dict http://docs.python.org/library/stdtypes.html#mapping-types-dict
我有一个实现映射 ABC 的类,但它失败了:
import collections
class Mapping(object):
def __init__(self, dict={}): self.dict=dict
def __iter__(self): return iter(self.dict)
def __iter__(self): return iter(self.dict)
def __len__(self): return len(self.dict)
def __contains__(self, value): return value in self.dict
def __getitem__(self, name): return self.dict[name]
m=Mapping({5:5})
dict(m)
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: cannot convert dictionary update sequence element #0 to a sequence
collections.Mapping.register(Mapping)
dict(m)
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: cannot convert dictionary update sequence element #0 to a sequence
但是,如果我的类是 collections.Mapping 的子类,那么它就可以正常工作:
import collections
class Mapping(collections.Mapping):
def __init__(self, dict={}): self.dict=dict
def __iter__(self): return iter(self.dict)
def __iter__(self): return iter(self.dict)
def __len__(self): return len(self.dict)
def __contains__(self, value): return value in self.dict
def __getitem__(self, name): return self.dict[name]
m=Mapping({5:5})
dict(m)
# {5: 5}
我认为 ABC 的全部要点是允许注册与子类化相同(无论如何对于 isinstance 和 issubclass)。那么这是怎么回事?