如何动态添加成员到类中
我的问题可以用这段代码简单地说明:
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成员之后,调用 otherobj 中的相应方法。怎么做呢?或者更具体地说:必须是什么 插入到“myname =”之后继续吗?
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 =' ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不确定这是否有效,但您可以尝试利用闭包:
Not sure if this works, but you could try to exploit closures:
如果方法被称为step1到stepn,你应该这样做:
如果你不知道名字,我不明白你想要实现什么。
If the methods are called step1 to stepn, you should do:
If you don't know the name, I don't understand what you're trying to achieve.