Python 如何找到metamethod的名称?
考虑以下示例:Python 如何找到metamethod的名称?,python,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(
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()
一种方法是使
元方法
成为类而不是函数
class metaMethod:
def __init__(self, name):
self.name = name
def __call__(*args, **kwargs):
print "method", self.name
一种方法是使
元方法
成为类而不是函数
class metaMethod:
def __init__(self, name):
self.name = name
def __call__(*args, **kwargs):
print "method", self.name
您必须以某种方式传递该参数,因此为什么不让
metaMethod
返回一个知道要打印什么的函数,而不是直接打印它呢?(我相信还有更多的方法可以做到这一点,这只是一种可能性。)
运行此脚本将打印
method foo
method bar
您必须以某种方式传递该参数,因此为什么不让
metaMethod
返回一个知道要打印什么的函数,而不是直接打印它呢?(我相信还有更多的方法可以做到这一点,这只是一种可能性。)
运行此脚本将打印
method foo
method bar
这正是我需要的,这正是我需要的。