簡體   English   中英

在哪里可以找到dict_keys類?

[英]Where can I find the dict_keys class?

如何直接在dict_keys類上獲取引用? 目前,我唯一能找到的方法是創建一個臨時dict對象並對其進行類型檢查。

>>> the_class = type({}.keys())
>>> the_class
<class 'dict_keys'>
>>> the_class.__module__
'builtins'
>>> import builtins
>>> builtins.dict_keys
AttributeError: module 'builtins' has no attribute 'dict_keys'

這就是您“應該”這樣做的方式,盡管我唯一煩惱的原因是修復Py 2.7中的一個錯誤,該錯誤中dict_keys不是collections.KeysView的虛擬子類,並且我使用該技術來執行操作Py3默認情況下會這樣做。

collections.abc (在Python中而不是C中實現) 將類型注冊collections.abc.KeysView的虛擬子類時, 它會執行以下操作

dict_keys = type({}.keys())
... many lines later ... 
KeysView.register(dict_keys)

因為該類沒有在Python層公開。 我認為如果Python本身沒有更好的方法來完成任務,那可能是正確的方法。 當然,您總是可以借用Python的成果:

# Can't use collections.abc itself, because it only imports stuff in
# _collections_abc.__all__, and dict_keys isn't in there
from _collections_abc import dict_keys

:-)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM