Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 18995

Accessing `self` and method name from dynamically-created methods

$
0
0

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:

  1. From _method_generator, I can access the class via cls, but I don't see a way to access the instance, e.g. self. How can I do this?
  2. In order to replicate the logic of save_foo, save_foo, save_foobar from _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?

Viewing all articles
Browse latest Browse all 18995

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>