This is one of the possible solutions. You can change the behavior of the method __iadd__.
class C(object):
def __init__(self):
self._x = MyList([])
def getx(self):
return self._x
def setx(self, value):
self._x = value
def delx(self):
del self._x
x = property(getx, setx, delx, "I'm the 'x' property.")
class MyList(list):
def __iadd__(self,x):
if hasattr(x,"__iter__"):
return super(MyList,self).__iadd__(x)
else:
return super(MyList,self).__iadd__([x])
Usage is as follows:
>>> c=C()
>>> c.x+=1
>>> c.x
[1]
>>> c.x+="test"
>>> c.x
[1,"test"]
>>> c.x+=[3,4]
>>> c.x
[1,"test",3,4]
To summarize: you cannot overload an operator inside Csetitem-method, because incrementing is not an operation for an attribute, but a basic list (since your attribute is just a variable pointing to that list, an object). See my comment and other answers.
source
share