I was trying to add some dynamic methods for some test case class. I basically tried the following where dynamically methods are added which just print the method names:
def add_methods(method_names):
def decorator(cls):
class NewClass(cls):
pass
for method_name in method_names:
setattr(NewClass, method_name, lambda x: print(method_name))
return NewClass
return decorator
class A:
pass
@add_methods(['method1', 'method2'])
class B:
pass
b = B()
b.method1()
b.method2()
This seems correct to me. But is not working well. The output is
method2
method2
Also, this works if i am assigning attributes like strings. But lambdas are just not working. Can anyone point me out in a good direction?