关于python:如何向类中动态添加成员

How to dynamically add members to class

我的问题可以用以下代码简单地说明:

1
2
3
4
5
6
7
8
9
10
11
12
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='之后插入继续?


如果方法被称为step1到stepn,则应执行以下操作:

1
2
3
4
5
6
7
8
9
10
11
12
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))

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


不确定这是否有效,但您可以尝试利用闭包:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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))