python - How to dynamically add members to class -
my question can illustrated 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): index in range(1, cond): setattr(self, 'step%u' % (index,), new.instancemethod(proceed, self, dispatch)
after instance of dispatch must have step1..stepn members, call corresponding methods in otherobj. how that? or more specifically: must inserted in proceed after 'myname =' ?
not sure if works, try 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):     index in range(1, cond):       name = 'step%u' % (index,)       setattr(self, name, new.instancemethod(make_proceed(name), self, dispatch)) 
Comments
Post a Comment