2011-02-28 105 views
1

我的問題可以通過這個代碼可以簡單說明:如何動態地添加成員

 
def proceed(self, *args): 
    myname = ??? 
    func = getattr(otherobj, myname) 
    result = func(*args) 
    # result = ... process result .. 
    return result 


class dispatch(object): 
    def __init__(self, cond=1): 
    for index in range(1, cond): 
     setattr(self, 'step%u' % (index,), new.instancemethod(proceed, self, dispatch) 

派遣該實例後,必須有step1..stepn成員,調用在otherobj 相應的方法。怎麼做?或者更具體地說:在'myname ='之後插入的內容必須是 ?

回答

2

不知道如果這個工程,但你可以嘗試利用瓶蓋:

def make_proceed(name): 
    def proceed(self, *args): 
     func = getattr(otherobj, name) 
     result = func(*args) 
     # result = ... process result .. 
     return result 
    return proceed 


class dispatch(object): 
    def __init__(self, cond=1): 
    for index in range(1, cond): 
     name = 'step%u' % (index,) 
     setattr(self, name, new.instancemethod(make_proceed(name), self, dispatch)) 
+0

是的,這是工作之一。再次感謝! – 2011-02-28 15:33:45

2

如果方法被稱爲步驟1到stepn,你應該做的:

def proceed(myname): 
    def fct(self, *args): 
     func = getattr(otherobj, myname) 
     result = func(*args) 
     return result 
    return fct 

class dispatch(object): 
    def __init__(self, cond=1): 
     for index in range(1, cond): 
      myname = "step%u" % (index,) 
      setattr(self, myname, new.instancemethod(proceed(myname), self, dispatch)) 

如果你不這樣做知道這個名字,我不明白你想要達到什麼目的。

+0

和我一樣的想法:)你忘了從'proceed'返回本地函數。 – 2011-02-28 15:19:02

+0

是的。但是你,Space_C0wb0y,也忘了... :)好的,謝謝你們的回答,我有想法! :) – 2011-02-28 15:25:00

+0

呃,糾正:) – PierreBdR 2011-02-28 16:38:32