考虑以下示例:
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
请您参考如下方法:
您必须以某种方式传递该参数,那么为什么不让 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
