Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import types
- class Klass:
- def __init__(self):
- self.x = 3
- user_funcs = {
- 'user_foo': '''
- def user_foo(self):
- return 'foo' * self.x
- ''',
- 'user_bar': '''
- def user_bar(self):
- return 'bar' * self.x
- '''
- }
- for n, f in user_funcs.items():
- exec(f)
- setattr(Klass, n, eval(n))
- o = Klass()
- for m in dir(o):
- if not m.startswith('user_'): continue
- print(f'dynamic call: {getattr(o, m)()}')
- o2 = Klass()
- o2.x = 4
- print(f'o.user_bar(): {o.user_bar()}')
- print(f'o2.user_bar(): {o2.user_bar()}')
- def m(self):
- return 'hoge' * self.x
- o2.user_bar = types.MethodType(m, o2)
- print(f'o.user_bar(): {getattr(o, "user_bar")()}')
- print(f're-def o2.user_bar(): {getattr(o2, "user_bar")()}')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement