【问题标题】:Adding dictionaries by value by writing + operator通过编写 + 运算符按值添加字典
【发布时间】:2019-12-28 12:58:33
【问题描述】:

我想为字典编写+ 运算符。

我知道在like here 之前有人问过类似的问题,但我想为字典编写+ 运算符。

我知道可以在 Python 的自定义类中重载运算符。但是我没有找到如何在内置类中重载运算符(如果这实际上可能的话)。另外,由于没有为 Python 中的字典定义 + 运算符,我想知道这是否可能?

我认为这个问题以前没有在 SO 上被问过,因为我找不到类似的东西。也许我只是没有找到合适的术语来搜索它。 Another link that might be useful for that question.

【问题讨论】:

标签: python dictionary operator-overloading operators


【解决方案1】:

我猜你想要做的是实现字典的添加方法 - 你可能想要使用自己的逻辑,我在这里使用更新方法来添加。您必须继承并重载 add 方法才能实现这一点。这是怎么做的。

class dicti(dict):
    def __add__(self, obj):
        temp = {}
        temp.update(self)
        temp.update(obj)
        return temp
a = dicti({'a':1,'b':2})
b = dicti({'c':2})
c = a+b
print(a) #outputs -> {'a': 1, 'b': 2}
print(b) #outputs -> {'c':2}
print(c) #outputs -> {'a': 1, 'b': 2, 'c': 2}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-24
    • 2016-08-07
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    相关资源
    最近更新 更多