【问题标题】:Python 2.7: applying str to collections.Counter and collections.defaultdictPython 2.7:将 str 应用于 collections.Counter 和 collections.defaultdict
【发布时间】:2016-06-18 17:58:33
【问题描述】:

collections.Counter 和 collections.defaultdict 都继承自 dict。那么它们之间有什么区别导致不相似的输出('class'和'type')?

import collections

print str(collections.Counter)
print str(collections.defaultdict)

输出:

<class 'collections.Counter'>
<type 'collections.defaultdict'>

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    恐怕你在这里的回答会归结为一些相当无聊的东西: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
    

    this answer 中所述,这是用 C 编写的内置扩展。

    如果你对deque(也是C)或collections中的其他一些用Python编写的类进行字符串化,你会注意到你会得到同样的行为:

    >>> from collections import deque
    >>> str(deque)
    "<type 'collections.deque'>"
    >>> from collections import OrderedDict
    >>> str(OrderedDict)
    "<class 'collections.OrderedDict'>"*
    

    【讨论】:

      猜你喜欢
      • 2016-02-11
      • 2019-12-01
      • 2017-01-18
      • 2015-09-14
      • 2016-04-08
      • 2021-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多