开发者

How to dynamically add members to class

My question can be simply illustrated by this code:

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)

After that instance of dispatch must have step1..stepn members, t开发者_开发百科hat call corresponding methods in otherobj. How to do that? Or more specifically: What must be inserted in proceed after 'myname =' ?


Not sure if this works, but you could try to exploit closures:

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


If the methods are called step1 to stepn, you should do:

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

If you don't know the name, I don't understand what you're trying to achieve.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜