如何在行为类似于字典的自定义 class 中使用 += 操作?
How to use += operation in custom class which behaves like dictionary?
我正在尝试实现 class['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}
我的 class 不需要 =
操作,所以上面的解决方案有效。无论如何,我想将其更改为 +=
以获得更好的可读性,以便每个人都可以看到那里到底发生了什么。我该怎么做?
x['b'] = 10
由x.__setitem__('b', 10)
实现。
x['b'] += 10
由x.__getitem__('b').__iadd__(10)
实现。
您不能在 Example
本身上定义方法来处理此处的 +=
。没有像__isetitem__
.
这样的"augmented item setter"
这里是根据@chepner 的回答修改的示例代码。谢谢,这解决了我的问题:
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}
我正在尝试实现 class['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}
我的 class 不需要 =
操作,所以上面的解决方案有效。无论如何,我想将其更改为 +=
以获得更好的可读性,以便每个人都可以看到那里到底发生了什么。我该怎么做?
x['b'] = 10
由x.__setitem__('b', 10)
实现。
x['b'] += 10
由x.__getitem__('b').__iadd__(10)
实现。
您不能在 Example
本身上定义方法来处理此处的 +=
。没有像__isetitem__
.
这里是根据@chepner 的回答修改的示例代码。谢谢,这解决了我的问题:
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}