2

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?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Be Wake Pandey
  • 491
  • 1
  • 5
  • 14
  • Thanks a lot!! I thought it was some issue with the use of `setattr()`. https://stackoverflow.com/questions/12423614/local-variables-in-nested-functions is definitely the answer I was seeking. – Be Wake Pandey Jul 29 '19 at 10:07

0 Answers0