【问题标题】:Is there a way to access the underlying dict from a dict subclass?有没有办法从 dict 子类访问底层 dict ?
【发布时间】:2023-04-01 02:55:01
【问题描述】:

我想构建一个特殊的 dict 类,它可以选择将其底层 dict 作为一个整体(而不仅仅是单个项目)导出,即像这样:

class CustomDict(dict):

    def export(self):
        return ???  # A dict instance

我知道我可以通过简单地动态构建导出字典来模拟这种行为,或者首先将项目存储在单独的类属性中,但我想知道是否有一种干净的方式来获取整个底层字典直接。 (还是我想多了?)

【问题讨论】:

  • 你能指定任何例子吗?
  • 好吧,如果它是一个子类,那么实际上并没有一个“底层”dict 实例。您继承了 dict 的所有属性,除了类型引用现在是 CustomDict,并且某些函数被覆盖。
  • return self 呢?
  • (我试图说明一点,任何CustomDict 都是dict 的实例。)
  • 有什么意义?你的意思是:阻止人们使用子类方法?不幸的是,如果不创建新字典或包装器,这在 Python 中是不可能的。

标签: python dictionary python-datamodel python-collections


【解决方案1】:

没有底层的 dict 实例。如果继承自 dict,CustomDict 类就是 dict 类并且拥有 dict 的所有方法和属性。因此,您在这里要做的只是将 CustomDict 实例传递到您希望将 dict 导出到的任何位置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    相关资源
    最近更新 更多