overload += in python for a mapping type
dictionary, operator-overloading, python
Solution
I think all you're missing is a def:
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}
Problem
I'd like to use a += notation for updating a dict-like object in Python. I want to have the same behavior as dict.update method. Here is my class (dictionary with "." access): ``` class sdict(dict): def __getattr__(self, attr): return self.get(attr, None) __setattr__= dict.__setitem__ __delattr__= dict.__delitem__ ``` I tried: ``` __iadd__ = dict.update ``` And: ``` def __iadd__(self, other): self.update(other) return self ``` but none of these work. (the first destroys the original dictionary and the second generates SyntaxError) Update: Second definition actually works. It didn't work for me because I forgot `def`. The first one doesn't work because dict.update returns None.