使用级联方法扩展字典

Extending dictionary with cascading methods

我正在扩展 python 中的字典 class:

import jmespath
import json

class superDict(dict):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
    
    def prettyPrint(self):
        print(self.pprettyPrint())
    
    def pprettyPrint(self):
        return json.dumps(self, indent=4, sort_keys=True, default=str)
    
    def search(self, pattern):
        return jmespath.search(pattern, self)
    
   ...

我希望能够做到:

regDict = {"key": "value"}
super = superDict(regDict)
super.search('patern').prettyPrint()

我这里的问题是 jmespath 可以 return 一个列表,所以我不能这样做:

    def search(self, pattern):
        return superDict(jmespath.search(pattern, self))

下一个想法是创建一个漂亮的打印 class,superDict 将继承它,也可以在搜索的 return 中使用:

class superDict(dict, prettyprint):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
    ...

    def search(self, pattern):
        return prettyprint(jmespath.search(pattern, self))

class prettyprint: ???

但我无法弄清楚 prettyprint class 会是什么样子才能正常工作。我基本上想不出一种优雅的方法来做到这一点。也许 init 中围绕 arg 类型的一些逻辑会更简单?

我最终使用了 new

class extensions:
    def prettyPrint(self):
        print(self.pprettyPrint())
        return self
    
    def pprettyPrint(self):
        return json.dumps(self, indent=4, sort_keys=True, default=str)
    
    def search(self, pattern):
        return exJSON(jmespath.search(pattern, self))

class exList(list, extensions):
    def prettyTable(self, headers):
        x = PrettyTable()
        x.field_names = headers
        for row in self:
            x.add_row(row.values())
        x.align = "l"
        print(x)
        return self

class exDict(dict, extensions):
    pass
        
class exStr(str, extensions):
    pass

class exJSON:
    def __new__(self, obj):
        if type(obj) is dict:
            return exDict(obj)
        if type(obj) is list:
            return exList(obj)
        if type(obj) is str:
            return exStr(obj)
        else:
            return obj