Advertisement
Guest User

Untitled

a guest
Dec 1st, 2022
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.32 KB | None | 0 0
  1. import inspect, types
  2.  
  3.  
  4. class Magic(dict):
  5.     def __init__(self, globals_, builtins):
  6.         self.globals_ = globals_
  7.         self.builtins = builtins
  8.        
  9.     def __getitem__(self, key):
  10.         try:
  11.             return self.globals_[key]
  12.         except KeyError:
  13.             pass
  14.        
  15.         try:
  16.             return self.builtins[key]
  17.         except KeyError:
  18.             pass
  19.            
  20.         frame = inspect.currentframe().f_back
  21.         try:
  22.             return getattr(frame.f_locals['self'], key)
  23.         finally:
  24.             frame = None
  25.  
  26.  
  27. def magic(cls):
  28.     for name, obj in vars(cls).items():
  29.         if not hasattr(obj, '__globals__'):
  30.             continue
  31.        
  32.         obj = types.FunctionType(
  33.             obj.__code__,
  34.             Magic(obj.__globals__, obj.__builtins__),
  35.             obj.__name__,
  36.             obj.__defaults__,
  37.             obj.__closure__,
  38.         )
  39.        
  40.         setattr(cls, name, obj)
  41.    
  42.     return cls
  43.  
  44.  
  45. @magic
  46. class ClassTester:
  47.     def __init__(self):
  48.         self.to_modify = "hello"
  49.  
  50.     def msg(self):
  51.         print(to_modify)
  52.         # do something with the to_modify function beside printing, since it's just an example
  53.  
  54.  
  55. Tester = ClassTester()
  56.  
  57. Tester.msg()
  58. Tester.to_modify = 20
  59. Tester.msg()
  60. Tester.to_modify = 30
  61. Tester.msg()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement