为什么集合运算符使用 dict_key 视图对象而不是等效的集合方法?

Why do set operators work with dict_key view objects but not the equivalent set methods?

编辑:可能重复。 只有在发布这个问题并查看 "related questions" 之后我才能找到 Why are set methods like .intersection() not supported on set-like objects?,这个问题可能与重复。

我正在尝试查看字典中的键是否是集合的子集,并发现 dict_keys 视图对象和集合 methods/operators.

的一些令人困惑的行为

Difference between a set and a view指出:

Only the dict.keys() dictionary view is always a set (insofar that it behaves like a set, but one with a live view of the dictionary)

https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects 文档指出

Keys views are set-like since their entries are unique and hashable. ... For set-like views, all of the operations defined for the abstract base class collections.abc.Set are available (for example, ==, <, or ^).

https://docs.python.org/2/library/stdtypes.html#set 集类型文档暗示运算符(<=、| 等)等同于方法 .issubset()union()

但以下代码并未反映这些断言:

> dic = {'first': 'a', 'second': 'b'}

> s = {'first', 'second', 'third'}

> dic.keys() <= s

True

> dic.keys().issubset(s)


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-354-fbf8f9744a80> in <module>
----> 1 dic.keys().issubset(s)

AttributeError: 'dict_keys' object has no attribute 'issubset'

然而

s.issuperset(dic.keys()) return True

当所有迹象都表明 .issubset() 方法可以工作时,为什么会出现不同的行为?

作为对 Why are set methods like .intersection() not supported on set-like objects? 的回答指出,

dict views only guarantee the API of collections.abc.Set, not to be equivalent to set itself (...) these set-like objects are not claimed to match set, or even frozenset, just collections.abc.Set (and) collections.abc.Set doesn't require any of the named methods aside from isdisjoint (which has no operator equivalent).