【问题标题】:overload += in python for a mapping type在 python 中重载 += 用于映射类型
【发布时间】:2012-04-05 03:46:09
【问题描述】:

我想使用 += 符号来更新 Python 中的类 dict 对象。我希望具有与 dict.update 方法相同的行为。这是我的课程(带有“.”访问权限的字典):

class sdict(dict):
    def __getattr__(self, attr):
        return self.get(attr, None)
    __setattr__= dict.__setitem__
    __delattr__= dict.__delitem__

我试过了:

__iadd__ = dict.update

还有:

def __iadd__(self, other):
    self.update(other)
    return self

但这些都不起作用。 (第一个破坏了原来的字典,第二个产生了 SyntaxError)

更新:
第二个定义确实有效。它对我不起作用,因为我忘记了def。第一个不起作用,因为 dict.update 返回 None。

【问题讨论】:

    标签: python dictionary operator-overloading


    【解决方案1】:

    我认为你所缺少的只是一个定义:

    class sdict(dict):
        def __getattr__(self, attr):
            return self.get(attr, None)
        __setattr__= dict.__setitem__
        __delattr__= dict.__delitem__
        def __iadd__(self, other):
            self.update(other)
            return self
    
    >>> a = sdict()
    >>> a.b = 3
    >>> a
    {'b': 3}
    >>> a.b
    3
    >>> a['b']
    3
    >>> a += {'fred': 3}
    >>> a
    {'b': 3, 'fred': 3}
    

    【讨论】:

    • 哎呀,打败我!在这里,给我宝贵的 +1
    • 哎呀...那太愚蠢了...谢谢您的回答!知道为什么 __iadd__ = dict.update 不起作用吗?
    • @user1084871:它打破了__iadd__返回赋值结果的要求。
    猜你喜欢
    • 2019-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-08
    相关资源
    最近更新 更多