我如何找到metamethod的名称?

时间:2013-08-01 12:30:38

标签: python

考虑以下示例:

import types

methods = ['foo', 'bar']

def metaMethod(self):
    print "method", "<name>"

class Egg:
    def __init__(self):
        for m in methods:
            self.__dict__[m] = types.MethodType(metaMethod, self)

e = Egg()
e.foo()
e.bar()

我应该写什么而不是"<name>",所以输出

method foo
method bar

2 个答案:

答案 0 :(得分:4)

你必须以某种方式传递该参数,那么为什么不让metaMethod返回一个知道要打印什么的函数,而不是直接打印它? (我确信有更多方法可以做到这一点,这只是一种可能性。)

import types

methods = ['foo', 'bar']

def metaMethod(self, m):
    def f(self):
        print "method", m
    return f

class Egg:
    def __init__(self):
        for m in methods:
            self.__dict__[m] = types.MethodType(metaMethod(self, m), self)

e = Egg()
e.foo()
e.bar()

运行此脚本打印

method foo
method bar

答案 1 :(得分:2)

一种方法是使metaMethod成为一个类而不是一个函数。

class metaMethod:
    def __init__(self, name):
        self.name = name
    def __call__(*args, **kwargs):
        print "method", self.name
相关问题