Advertisement
cd62131

Python Metaprogramming

Apr 2nd, 2019
507
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.75 KB | None | 0 0
  1. import types
  2.  
  3.  
  4. class Klass:
  5.     def __init__(self):
  6.         self.x = 3
  7.  
  8.  
  9. user_funcs = {
  10.     'user_foo': '''
  11. def user_foo(self):
  12.    return 'foo' * self.x
  13. ''',
  14.     'user_bar': '''
  15. def user_bar(self):
  16.    return 'bar' * self.x
  17. '''
  18. }
  19.  
  20. for n, f in user_funcs.items():
  21.     exec(f)
  22.     setattr(Klass, n, eval(n))
  23.  
  24. o = Klass()
  25. for m in dir(o):
  26.     if not m.startswith('user_'): continue
  27.     print(f'dynamic call: {getattr(o, m)()}')
  28.  
  29. o2 = Klass()
  30. o2.x = 4
  31. print(f'o.user_bar(): {o.user_bar()}')
  32. print(f'o2.user_bar(): {o2.user_bar()}')
  33.  
  34.  
  35. def m(self):
  36.     return 'hoge' * self.x
  37.  
  38.  
  39. o2.user_bar = types.MethodType(m, o2)
  40. print(f'o.user_bar(): {getattr(o, "user_bar")()}')
  41. print(f're-def o2.user_bar(): {getattr(o2, "user_bar")()}')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement