首页 文章

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

提问于
浏览
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 回答

  • 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))
    

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

  • 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))
    

相关问题