Skip to content Skip to sidebar Skip to footer

How To Dynamically Override __setitem__? (no Subclass)

I'm not able to override some builtin functions, such as '__setitem__', in Python2.7 (although the same occurs in previous versions I tested) Although I know this is easy to do via

Solution 1:

For old-style classes, special methods were looked up on the instance each time they were needed. New-style classes only look up special methods on the type of the instance, not in the instance's dictionary itself -- that's why you see the behaviour you see.

(In case you don't know -- a new-style class is a class directly or indirectly derived from object.)

Solution 2:

As Sven Marnach says, the problem is that for new-style classes, indexed assignment uses the __setitem__ defined by the class. But it's not hard to get around this problem. The solution, as is so often the case, involves another level of indirection. This isn't a great design, but it seems like the obvious way to do what you want:

>>>classFoo(object):...def__setitem__(self, k, v):...return self._instance_setitem(k, v)...def_instance_setitem(self, k, v):...print'old setitem'...>>>defnew_setitem(self, k, v):...print'new setitem'...>>>f[0] = 0
old setitem
>>>f._instance_setitem = types.MethodType(new_setitem, f, Foo)>>>f[0] = 0
new setitem

Post a Comment for "How To Dynamically Override __setitem__? (no Subclass)"