如何动态地向成员添加成员

时间:2011-02-28 15:03:47

标签: python class dynamic members

我的问题可以通过以下代码简单说明:

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 个答案:

答案 0 :(得分: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))

答案 1 :(得分:2)

如果方法被称为step1到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))

如果你不知道这个名字,我不明白你想要达到的目的。