Python2.7中使用方法名字符串的动态方法调用
我有一个元组,它列出了类的方法,如:Python2.7中使用方法名字符串的动态方法调用,python,python-2.7,Python,Python 2.7,我有一个元组,它列出了类的方法,如: t = ('methA','methB','methC','methD','methE','methF') 等等 现在我需要根据用户的选择动态调用这些方法。将根据索引调用这些方法。因此,如果用户选择“0”,则调用methA,如果选择“5”,则调用methF 我的方法如下: def makeSelection(self, selected): #methodname = t[selected] #but as this is from wi
t = ('methA','methB','methC','methD','methE','methF')
等等
现在我需要根据用户的选择动态调用这些方法。将根据索引调用这些方法。因此,如果用户选择“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
我已经设法用
eval
解决了一些问题,但它会产生错误,而且一点也不优雅。如果要对对象(包括导入的模块)调用方法,可以使用:
getattr(obj, method_name)(*args) # for this question: use t[i], not method_name
例如:
>>> s = 'hello'
>>> getattr(s, 'replace')('l', 'y')
'heyyo'
如果需要调用当前模块中的函数
getattr(sys.modules[__name__], method_name)(*args)
其中,args
是要发送的参数列表或元组,或者您可以像在任何其他函数中一样在调用中列出它们。由于您所在的方法试图对同一对象调用另一个方法,请将第一个方法与self
一起使用,以代替obj
获取一个对象和一个字符串,并在该对象中执行属性查找,如果该属性存在,则返回该属性obj.x
和getattr(obj,'x')
实现相同的结果。如果您想进一步研究这种反射,还可以使用setattr
、hasattr
和delattr
函数
完全替代的方法:
在注意到这个答案所受到的关注之后,我将提出一种不同的方法。我假设存在一些方法
def methA(*args): print 'hello from methA'
def methB(*args): print 'bonjour de methB'
def methC(*args): print 'hola de methC'
为了使每个方法对应一个数字(选择),我构建了一个字典,将数字映射到方法本身
id_to_method = {
0: methA,
1: methB,
2: methC,
}
鉴于此,id\u to\u方法[0]()
将调用methA
。它由两部分组成,首先是id\u to\u方法[0]
,它从字典中获取函数对象,然后()
调用它。我还可以将参数id\u传递给方法[0](“whatever”、“args”、“I”、“want”)
在实际代码中,考虑到上述情况,您可能会
choice = int(raw_input('Please make a selection'))
id_to_method[choice](arg1, arg2, arg3) # or maybe no arguments, whatever you want
如果我们考虑实例方法,一个好的解决方案是什么?例如:设想您现在编写的方法包括自参数:def methA(self,*args):打印'hello from meta',但我想在类中构建字典(这样就可以在不必有实例的情况下读取键)而不是在构造函数中。你怎么能这样做呢?你可以像这里一样使用未绑定的方法和
getattr
。我不确定我是否理解你想要什么。我的类X的对象有可选的“探索”“方法。函数y与用户交互并调用所需的探索方法。而不是如果elif-elif-。。。我更喜欢查字典,因为它看起来更好。另外,如果字典是一个类变量,我可以从外部访问它的键。这里的问题是,这些探索方法依赖于实例变量。我也想过(并实现了)getattr的技巧,但它看起来一点也不漂亮。@tamzord很抱歉,我已经好几个星期没玩了。使用未绑定方法有什么问题?getattr(self,dynamic_method_name)(args)用于动态访问类的方法中的方法