I have a class of which several methods could be dynamically generated, which would save some boilerplate:
class A: def save_foo(self, **kwargs): do_foo_stuff_here() def save_bar(self, **kwargs): do_bar_stuff_here() def save_foobar(self, **kwargs): do_foobar_stuff_here()This stackoverflow answer taught me about that I can create the methods using
class A(): passdef _method_generator(cls, **kwargs): if method_name == "save_foo": do_foo_stuff_here() elif method_name == "save_foo": do_bar_stuff_here() elif method_name == "save_foobar": do_foobar_stuff_here()for method_name in ["save_foo", "save_bar", "save_foobar"]: setattr(A, method_name, classmethod(_method_generator))My problem is twofold:
- From
_method_generator, I can access the class viacls, but I don't see a way to access the instance, e.g.self. How can I do this? - In order to replicate the logic of
save_foo,save_foo,save_foobarfrom_method_generator, I need to know which was called. I've seen answers like this one, but that gives me_method_generator, not the method/attribute that called it. How can I get this?