Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import inspect, types
- class Magic(dict):
- def __init__(self, globals_, builtins):
- self.globals_ = globals_
- self.builtins = builtins
- def __getitem__(self, key):
- try:
- return self.globals_[key]
- except KeyError:
- pass
- try:
- return self.builtins[key]
- except KeyError:
- pass
- frame = inspect.currentframe().f_back
- try:
- return getattr(frame.f_locals['self'], key)
- finally:
- frame = None
- def magic(cls):
- for name, obj in vars(cls).items():
- if not hasattr(obj, '__globals__'):
- continue
- obj = types.FunctionType(
- obj.__code__,
- Magic(obj.__globals__, obj.__builtins__),
- obj.__name__,
- obj.__defaults__,
- obj.__closure__,
- )
- setattr(cls, name, obj)
- return cls
- @magic
- class ClassTester:
- def __init__(self):
- self.to_modify = "hello"
- def msg(self):
- print(to_modify)
- # do something with the to_modify function beside printing, since it's just an example
- Tester = ClassTester()
- Tester.msg()
- Tester.to_modify = 20
- Tester.msg()
- Tester.to_modify = 30
- Tester.msg()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement