view
对象基本上是“空”代理。他们指向原始字典。
不幸的是,当前的字典视图对象并不是真正可重用的。引用源代码:
/* TODO(guido): The views objects are not complete:
* support more set operations
* support arbitrary mappings?
- either these should be static or exported in dictobject.h
- if public then they should probably be in builtins
*/
注意support arbitrary mappings
条目;这些对象不支持任意映射,我们也不能从 Python 代码创建新实例或子类化它们:
>>> type({}.viewkeys())({})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot create 'dict_keys' instances
>>> class MyView(type({}.viewkeys())): pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Error when calling the metaclass bases
type 'dict_keys' is not an acceptable base type
您被迫创建自己的并实现视图对象支持的所有钩子:
class DictKeys(object):
def __init__(self, parent):
self.parent = parent
def __len__(self):
return len(self.parent)
def __contains__(self, key):
return key in self.parent
def __iter__(self):
return iter(self.parent)
等等
原始对象实现的方法是:
>>> dir({}.viewkeys())
['__and__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__']
, __and__
, __or__
, __sub__
, __xor__
,和方法实现对 , 和 运算符的覆盖__rand__
以提供集合操作。__ror__
__rsub__
__rxor__
&
|
^
如果您在阅读 C 代码时相当安全,请查看视图对象实现以了解它们如何实现其方法。