如何动态添加类的成员

1 投票
2 回答
1156 浏览
提问于 2025-04-16 12:40

我的问题可以用这段代码简单说明:

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这些成员,它们会调用其他对象中的相应方法。那该怎么做呢?更具体一点说:在'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))

撰写回答