0

I have class:

class SimpleClass:
    def __init__(self):
        pass

    def init_levels(self):
        levels = get_levels_list()
        for level in levels:
            Transplant(foo, Simplelog, method_name=level)

Transplant is a class for dynamically adding methods to class:

class Transplant:
    def __init__(self, method, host, method_name=None):
        self.host = host
        self.method = method
        self.method_name = method_name
        setattr(host, method_name or method.__name__, self)

    def __call__(self, *args, **kwargs):
        nargs = [self.host]
        nargs.extend(args)
        return apply(self.method, nargs, kwargs)

Foo is a function for "transplanting":

def foo(self):
    return

How can I get called method name inside foo?

For example I execute:

simpleinst = SimpleClass()
simpleinst.init_levels()

How can I modify my code for getting called method name in foo definition body?

3 Answers 3

2

You'll have to pass it in explicitly:

class Transplant:
    def __init__(self, method, host, method_name=None):
        self.host = host
        self.method = method
        self.method_name = method_name or method.__name__
        setattr(host, method_name or method.__name__, self)

    def __call__(self, *args, **kwargs):
        nargs = [self.host, self.method_name]
        nargs.extend(args)
        return apply(self.method, nargs, kwargs)

and extend foo to accept that as an argument.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank! I just replace nargs = [self.host] to nargs = [self] and now I have all method parameters.
1

Have you looked at getattr?

getattr(self, "method")

Comments

0

You could do it with a function factory, make_foo:

The key step is redefining the function's func_name attribute:

foo.func_name = name

class SimpleClass:
    def init_levels(self):
        levels = ['foo', 'bar']
        for level in levels:
            # Your original code defined this on `SimpleLog`. Did you mean `SimpleClass`?
            setattr(SimpleClass, level, make_foo(level))

def make_foo(name):
    def foo(self):
        print('{n} has been called'.format(n = foo.func_name))

    foo.func_name = name
    return foo

simpleinst = SimpleClass()
simpleinst.init_levels()
simpleinst.foo()
# foo has been called
simpleinst.bar()
# bar has been called

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.