Python 如何使用+;=自定义类中的操作,其行为类似于字典?

Python 如何使用+;=自定义类中的操作,其行为类似于字典?,python,dictionary,overloading,Python,Dictionary,Overloading,我试图实现像类['key']+=value这样的行为。到目前为止,我的结论是: class Example: def __init__(self): self.x = {'a': 0, 'b': 3} def __setitem__(self, key, item): self.x[key] += item x = Example() x['b'] = 10 print(x.x) #{'a': 0, 'b': 13} 在我的类中我不需要=操作

我试图实现像
类['key']+=value
这样的行为。到目前为止,我的结论是:

class Example:
    def __init__(self):
        self.x = {'a': 0, 'b': 3}

    def __setitem__(self, key, item):
        self.x[key] += item

x = Example()
x['b'] = 10
print(x.x) #{'a': 0, 'b': 13}

在我的类中我不需要
=
操作,所以上面的解决方案是有效的。不管怎样,我想把它改成
+=
,以提高可读性,让每个人都能看到那里到底发生了什么。我该怎么做?

x['b']=10
x.实现

x['b']+=10
x.\uuuu getitem\uuuuuu('b')。\uuuuu iadd\uuuuuu10)
实现


您不能在
示例
本身上定义一个方法来处理
+=
。没有像
\uu isetitem\uuu
x['b']=10
这样的“增强项设置器”是由
x实现的

x['b']+=10
x.\uuuu getitem\uuuuuu('b')。\uuuuu iadd\uuuuuu10)
实现


您不能在
示例
本身上定义一个方法来处理
+=
。没有像
\uu isetitem\uuu

这样的“增强项目设置器”,这里是根据@chepner answer修改的示例代码。谢谢,这解决了我的问题:

class Example:
    def __init__(self):
        self.x = {'a': 0, 'b': 3}

    def __setitem__(self, key, item):
        self.x[key] = item

    def __getitem__(self, key):
        return self.x[key]

    def __iadd__(self, key, other):
         return self.__getitem__(key) + other

x = Example()
x['b'] = 21
x['b'] += 10

print(x.x) #{'a': 0, 'b': 31}

下面是根据@chepner-answer修改的示例代码。谢谢,这解决了我的问题:

class Example:
    def __init__(self):
        self.x = {'a': 0, 'b': 3}

    def __setitem__(self, key, item):
        self.x[key] = item

    def __getitem__(self, key):
        return self.x[key]

    def __iadd__(self, key, other):
         return self.__getitem__(key) + other

x = Example()
x['b'] = 21
x['b'] += 10

print(x.x) #{'a': 0, 'b': 31}