2013-03-25 105 views
1

我想動態地在類__init__方法中創建一堆方法。迄今爲止還沒有運氣。python類中動態分配方法

CODE:

class Clas(object): 
    def __init__(self): 
     for i in ['hello', 'world', 'app']: 
      def method(): 
       print i 
      setattr(self, i, method) 

比我箱子的方法和呼叫方法是fitst列表。

>> instance = Clas() 

>> instance.hello() 

'app' 

我希望它打印hello沒有app。問題是什麼? 此外,這些動態分配方法中提到的內存相同的功能,即使我做copy.copy(method)

回答

6

您需要綁定i正確:

for i in ['hello', 'world', 'app']: 
    def method(i=i): 
     print i 
    setattr(self, i, method) 

i變量則是由本地method 。另一種選擇是使用新的示波器(單獨功能)生成您的方法:

def method_factory(i): 
    def method(): 
     print i 
    return method 

for i in ['hello', 'world', 'app']: 
    setattr(self, i, method_factory(i))