【问题标题】:Why does class derived from dict not show contains keys为什么从dict派生的类不显示包含键
【发布时间】:2014-05-30 04:47:49
【问题描述】:

使用此代码:

    class MyDict(dict):
        def __setitem__(self, k, v):
            print 'assignment', k, v
            self.__dict__[k] = v

    nsg = MyDict()
    nsg["b"] = 123
    print "G is: ", nsg

打印出来

assignment b 123
G is: {}

如果我添加

def __str__(self):
    return self.__dict__.__str__()

有效:

assignment b 123
G is:  {'b': 123}

同样,如果我打印 G["b"],我会得到一个 KeyError,除非 __getitem__(self) 返回 self.__dict__[k]

为什么没有自动找到父类dict,如__str____getitem__

【问题讨论】:

    标签: python dictionary derived-class


    【解决方案1】:

    dict 对象不在__dict__ 属性中存储键和值;怎么可能呢,__dict__ 属性本身就是一个dict 对象!

    使用重写的__setitem__ 方法添加到字典中;最佳做法是使用super() 查找原始方法:

    class MyDict(dict):
        def __setitem__(self, k, v):
            print 'assignment', k, v
            super(MyDict, self).__setitem__(k, v)
    

    您也可以使用未绑定的dict.__setitem__ 方法:

    class MyDict(dict):
        def __setitem__(self, k, v):
            print 'assignment', k, v
            dict.__setitem__(self, k, v)
    

    除非那会硬编码该方法,而不是您的自定义 myDict 类的 len 子类注入另一个中介 __setitem__ 方法。

    【讨论】:

    • 完美运行。所以这意味着 dict 有一个 __dict__ (因为在 throw 中没有异常,print self.__dict__ 打印“{}”),但不使用它......奇怪!在任何情况下,使用您的技术,键值对都会添加到 dict 本身(不是__dict__),因此无需定义所有其他方法(__str____getitem__ 等)。
    • 您的 子类 有一个 __dict__,因为它是一个自定义类并且不使用 __slots__
    猜你喜欢
    • 2022-08-07
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    • 2011-06-17
    • 2016-05-28
    • 1970-01-01
    • 2013-10-26
    相关资源
    最近更新 更多