如何访问 collection.Counter 的内部字典以使用继承扩展 Child class 的功能?

How to access internal dictionary of collection.Counter to extend the functionality of Child class by using Inheritance?

我想在 collections.Counter 中添加 2 个函数来为其添加排序和返回最小 n 值的功能。为此,我需要访问内部词典,但我不知道如何使用它。我检查了使用 vars(Counter) 创建的 class 的内部变量以及使用 dir(Counter) 创建的 dunder 和其他函数。由于字典我们在创建 class 后返回,所以方法和变量在构造函数本身中。因此,为了查看我使用的功能,dir(Counter.__init__) 但找不到好用的东西,因为那里只有方法。

例如,如果我做 counter = Counter(iterable),我需要访问那个 self.counter 变量 Inside class 本身,但我不需要变量将是。

下面是我要实现的代码

from collections import Counter
import heapq
from operator import itemgetter


class CounterNew(Counter):
    '''
    Increase the functionality of collections.Counter() class
    '''
    def least_common(n:int)->list:
        '''
        Get the least common elements
        args:
            n: How many elements you want to have which have the lowest frequency
        out: list of tuples as [(key,frequency)]
        '''
        return heapq.nsmallest(n, counter.items(), key=lambda x:x[1])
    
    
    def sort_by_freq(self,reverse:bool=False)->dict:
        '''
        Sort the Dictonary by frequency counts
        args:
            reverse: Whether to sort the dictonary in increasing or decreasing order
        out: Sorted dictonary
        '''
        self.sorted = sorted(counter.items(), key=lambda x:x[1], reverse=reverse) # How can I sort the internal dictonary that is returned by class
        return self.sorted

collections.Counterdict 的子类。所以它不包含实例变量中的字典,字典就是实例本身。因此,如果您需要访问字典,只需使用 self.

您在 sort_by_freq 方法中做同样的事情。因为你想把它return变成dict,你需要调用dict()把它转换回字典。

def least_common(self, n:int)->list:
    return heapq.nsmallest(n, self.items(), key=lambda x:x[1])

def sort_by_freq(self,reverse:bool=False)->dict:
    '''
    Sort the Dictonary by frequency counts
    args:
        reverse: Whether to sort the dictonary in increasing or decreasing order
    out: Sorted dictonary
    '''
    self.sorted = dict(sorted(self.items(), key=lambda x:x[1], reverse=reverse))
    return self.sorted