![](/img/trans.png)
[英]Why is collections.Counter uppercase and collections.defaultdict is not?
[英]Python 2.7: applying str to collections.Counter and collections.defaultdict
collections.Counter和collections.defaultdict都是從dict繼承而來的。 那么它們之間有什么區別導致不相似的輸出(“類”和“類型”)?
import collections
print str(collections.Counter)
print str(collections.defaultdict)
輸出:
<class 'collections.Counter'>
<type 'collections.defaultdict'>
我擔心你的答案歸結為一些相當無聊的東西: Counter
是用Python編寫的,而defaultdict
是用C語言編寫的。
這是collections.py
。 請注意,您可以向下滾動並找到Counter
的標准類定義:
########################################################################
### Counter
########################################################################
class Counter(dict):
'''Dict subclass for counting hashable items. Sometimes called a bag
or multiset. Elements are stored as dictionary keys and their counts
are stored as dictionary values.
...
'''
然而, defaultdict
從進口_collections
:
from _collections import deque, defaultdict
如本回答所述 ,這是一個用C編寫的內置擴展。
如果你使用Python編寫的collections
中的string-ify deque
(也是C)或其他類,你會發現你會遇到同樣的行為:
>>> from collections import deque
>>> str(deque)
"<type 'collections.deque'>"
>>> from collections import OrderedDict
>>> str(OrderedDict)
"<class 'collections.OrderedDict'>"*
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.