[英]How do I find the name of metamethod?
考慮以下示例:
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
一種方法是使metaMethod
成為類而不是函數。
class metaMethod:
def __init__(self, name):
self.name = name
def __call__(*args, **kwargs):
print "method", self.name
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.