簡體   English   中英

Python 2.7:將str應用於collections.Counter和collections.defaultdict

[英]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.

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