I've found that I'm able to override methods like __iadd__
of built-in classes, but I can't change their behavior merely by reassigning __iadd__
:
class OverrideList(list):
def __iadd__(self, x):
print("You'll see this")
return list.__iadd__(self, x)
class ReassignList(list):
def iadd(self, x):
print("You'll never see this")
return list.__iadd__(self, x)
def __init__(self, *args, **kw):
list.__init__(self, *args, **kw)
self.__iadd__ = self.iadd
ol = OverrideList()
ol += range(3)
rl = ReassignList()
rl += range(3)
Is there something I can do that will get me to ReassignList.iadd?
I initially thought that the funny thing about iadd was that it's a "slot wrapper", not a method, but this snippet makes me skeptical:
class OverrideThenReassign(OverrideList):
def iadd(self, x):
print("You won't see this either")
return list.__iadd__(self, x)
def __init__(self, *args, **kw):
list.__init__(self, *args, **kw)
print("OverrideThenReassign.__iadd__ starts out as {} not as a slot wrapper".format(self.__iadd__.__class__))
self.__iadd__ = self.iadd
The motivation is generalize a technique for writing a PersistentList
subclass of list
by wrapping methods with code to save the data structure in question to disk. There's a draft here.
EDIT: this question is approximately the same as this one. That question is buried in numpy gobbledygook so I'm not going to flag this as a duplicate unless a SO superstar advises doing so.