简体   繁体   English

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

[英]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, that call corresponding methods in otherobj. 在调度实例之后必须有step1..stepn成员,在otherobj中调用相应的方法。 How to do that? 怎么做? Or more specifically: What must be inserted in proceed after 'myname =' ? 或者更具体地说:在'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: 如果方法被称为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))

If you don't know the name, I don't understand what you're trying to achieve. 如果你不知道这个名字,我不明白你想要达到的目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM