如何在Python2.7中将用户生成的字符串转换为方法或函数调用?你能搜索dir(对象)以查看方法/函数是否存在然后调用该方法吗?
答案 0 :(得分:2)
最好只是尝试调用该方法,如果它不存在,它将抛出异常,你可以处理。
>>> try: obj.a_method()
... except AttributeError: print 'No method a_method in this object'
...
No method a_method in this object
>>>
答案 1 :(得分:2)
您可以尝试以下方式:
ui = input("Try something: ")
if ui in dir():
func = eval(ui)
func()
例如:
>>> def test():
return "foo"
>>> if "test" in dir():
func = eval("test")
func()
'foo'
答案 2 :(得分:1)
函数名称只是属性,因此您可以这样做:
try:
getattr(object, methodname)()
except AttributeError as e:
print 'Method %s not found or not callable!'%methodname
答案 3 :(得分:0)
您可以使用globals
返回模块__dict__
def command_1():
print "You are in command 1"
def command_2():
print "You are in command 2"
def default():
print "Can't find your command"
func = raw_input("ENTER YOUR COMMAND: ")
your_func = globals().get(func, None)
if your_func is None:
your_func = default
your_func()
ENTER YOUR COMMAND: command_1
You are in command 1
或
ENTER YOUR COMMAND: aaa
Can't find your command