fork download
  1. import types
  2.  
  3. class customizable:
  4. def __init__(self, method):
  5. self.method = method
  6.  
  7. def __set_name__(self, owner, name):
  8. self.name = name
  9.  
  10. def __get__(self, obj, obj_type=None):
  11. if obj:
  12. try:
  13. return vars(obj)[self.name]
  14. except KeyError:
  15. return self.method.__get__(obj, obj_type)
  16. return self.method
  17.  
  18. class Foo():
  19. @customizable
  20. def __getitem__(self, x):
  21. return x
  22.  
  23. def new_get(self, x):
  24. return x + 1
  25.  
  26. x = Foo()
  27. y = Foo()
  28. x.__getitem__ = types.MethodType(new_get, x)
  29. print(Foo.__getitem__)
  30. print(x[42])
  31. print(y[42])
Success #stdin #stdout 0.02s 9840KB
stdin
Standard input is empty
stdout
<function Foo.__getitem__ at 0x154f7e55c310>
43
42