There is a magic Python method __setitem__for assigning =to sequence types. Are there magic methods for advanced assignment +=at the container level? . The operation seems to be gracefully broken down into an extended element type assignment. This is logical. But there is a magic method for everything else, I thought that for these operators there should be a set of methods for the type of sequence. Did I miss this?
The application is a kind of database. Think of an implementation __getitem__with SELECT and __setitem__with INSERT. For UPDATE there should be something like __additem__, etc.
from __future__ import print_function
class Item(object):
def __init__(self, value):
self.value = value
def __str__(self):
return "Item " + str(self.value)
def __iadd__(self, other):
print("Item iadd", self, other)
return Item(self.value + "+" + other.value)
class Container(object):
def __getitem__(self, key):
print("Container getitem", key)
return Item(key)
def __setitem__(self, key, value):
print("Container setitem", key, value)
return self
def __additem__(self, key, value):
print("Container additem would be nice", key, value)
return self
Here's SELECT:
>>> c = Container()
>>> _ = c['key']
Container getitem key
Here's the INSERT:
>>> c['key'] = Item('other')
Container setitem key Item other
How to implement UPDATE? Without breaking into SELECT and INSERT:
>>> c['key'] += Item('other')
Container getitem key
Item iadd Item key Item other
Container setitem key Item key+other
, , ? Item?
python Python:
http://pythonfiddle.com/add-item-for-sequence/
A self[key] += value