You can make __getitem__
a descriptor that would first try to return the same-named attribute of a given instance before defaulting to binding the original method to the instance:
class customizable:
def __init__(self, method):
self.method = method
def __set_name__(self, owner, name):
self.name = name
def __get__(self, obj, obj_type=None):
if obj:
try:
return vars(obj)[self.name]
except KeyError:
return self.method.__get__(obj, obj_type)
return self.method
so that:
import types
class Foo():
@customizable
def __getitem__(self, x):
return x
def new_get(self, x):
return x + 1
x = Foo()
y = Foo()
x.__getitem__ = types.MethodType(new_get, x)
print(Foo.__getitem__)
print(x[42])
print(y[42])
outputs:
<function Foo.__getitem__ at 0x154f7e55c310>
43
42
Demo: https://ideone.com/fLjlWD
Note that if you don't own the code of Foo
you can either patch its __getitem__
method with the descriptor:
Foo.__getitem__ = customizable(Foo.__getitem__) # would not work on built-in types
or override __getitem__
in a subclass of Foo
instead:
class Bar(Foo):
__getitem__ = customizable(Foo.__getitem__)
__getitem__
. (The idea is to modify an object, pass it through some existing code and record the time it took at each call of a method).