bha*_*arc 13 python python-2.7
我有一个元组列出了类的方法,如:
t = ('methA','methB','methC','methD','methE','methF')
Run Code Online (Sandbox Code Playgroud)
等等..
现在我需要根据用户选择动态调用这些方法.将根据索引调用这些方法.因此,如果用户选择"0",methA则调用(如果为"5" methF).
我这样做的方法如下:
def makeSelection(self, selected):
#methodname = t[selected]
#but as this is from within the class , it has to be appended with 'self.'methodname
# also need to pass some arguments locally calculated here
Run Code Online (Sandbox Code Playgroud)
我已经设法解决了一些事情,eval但它产生错误并且一点也不优雅.
Rya*_*ing 30
如果您在对象(包括导入的模块)上调用方法,则可以使用:
getattr(obj, method_name)(*args) # for this question: use t[i], not method_name
Run Code Online (Sandbox Code Playgroud)
如果需要在当前模块中调用函数
>>> s = 'hello'
>>> getattr(s, 'replace')('l', 'y')
'heyyo'
Run Code Online (Sandbox Code Playgroud)
哪个args是要发送的参数的列表或元组,或者您可以像调用任何其他函数一样在调用中列出它们.由于您正在尝试在同一对象上调用另一个方法,因此请使用第一个方法self代替obj
getattr获取一个对象和一个字符串,并在该对象中执行属性查找,如果该属性存在则返回该属性. obj.x并getattr(obj, 'x')实现相同的结果.如果你想进一步研究这种反射setattr,还有hasattr,和delattr函数.
一种完全替代的方法:
在注意到这个答案得到的关注之后,我将建议采用不同的方法来处理你正在做的事情.我假设存在一些方法
getattr(sys.modules[__name__], method_name)(*args)
Run Code Online (Sandbox Code Playgroud)
为了使每个方法对应一个数字(选择),我构建了一个字典,将数字映射到方法本身
def methA(*args): print 'hello from methA'
def methB(*args): print 'bonjour de methB'
def methC(*args): print 'hola de methC'
Run Code Online (Sandbox Code Playgroud)
鉴于此,id_to_method[0]()将调用methA.它是两部分,首先是id_to_method[0]从字典中获取函数对象,然后()调用它.我也可以传递参数id_to_method[0]("whatever", "args", "I", "want)
在您的真实代码中,鉴于上述情况,您可能会有类似的东西
id_to_method = {
0: methA,
1: methB,
2: methC,
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18039 次 |
| 最近记录: |