简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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