2013-08-01 52 views
1

請看下面的例子:如何找到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 

回答

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 
+0

這正是我需要的。 – rmflow

2

一種方法是使metaMethod一類,而不是一個功能。

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