如何在Python中获取被调用方法的名称(动态添加)?

时间:2013-02-04 11:04:04

标签: python oop methods

我上课了:

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是一个用于向类动态添加方法的类:

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是“移植”的功能:

def foo(self):
    return

如何在foo中获取被调用的方法名称?

例如我执行:

simpleinst = SimpleClass()
simpleinst.init_levels()

如何在foo定义体中修改我的代码以获取被调用的方法名?

3 个答案:

答案 0 :(得分:2)

你必须明确地传递它:

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)

并扩展foo以接受它作为参数。

答案 1 :(得分:1)

你看过getattr了吗?

getattr(self, "method")

答案 2 :(得分:0)

您可以使用功能工厂make_foo

执行此操作

关键步骤是重新定义函数的func_name属性:

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