【问题标题】:Python check if a string is in dir() and if it is convert that string into a method/function callPython 检查字符串是否在 dir() 中以及是否将该字符串转换为方法/函数调用
【发布时间】:2014-03-11 17:44:16
【问题描述】:

如何在 Python2.7 中将用户生成的字符串转换为方法或函数调用?你可以搜索 dir(object) 以查看方法/函数是否存在然后调用该方法吗?

【问题讨论】:

    标签: python function methods


    【解决方案1】:

    最好只是尝试调用该方法,如果它不存在它会抛出一个异常,你可以处理。

    >>> try: obj.a_method()
    ... except AttributeError: print 'No method a_method in this object'
    ... 
    No method a_method in this object
    >>> 
    

    【讨论】:

    • 这解决了我的具体问题,谢谢。
    【解决方案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'
    

    【讨论】:

    • 这里的想法是,既然你正在检查dir,所以只会执行存在的对象,eval 是安全的吗?
    • @CorleyBrigman 类似的东西,是的,或者肯定比evaling 任意字符串更安全
    • 如果 dir(object) 调用返回一个列表或元组怎么办?我试过用你的方式没有运气。是因为我试图用一个 Module 对象来做到这一点吗?具体来说,我正在尝试逐步遍历 ast 对象,只是为了与我的抽象语法树进行交互。
    • @baallezx 我认为你需要修改你的问题,提供更多关于你在做什么以及你到底在哪里卡住的信息(“没有运气”是否意味着错误(提供回溯)?意外输出(提供输入以及预期和实际输出)?)
    【解决方案3】:

    函数名只是属性,所以你可以这样做:

    try:
        getattr(object, methodname)()
    except AttributeError as e:
        print 'Method %s not found or not callable!'%methodname
    

    【讨论】:

      【解决方案4】:

      你可以使用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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-15
        • 1970-01-01
        • 2010-10-18
        • 1970-01-01
        • 2016-10-07
        • 1970-01-01
        相关资源
        最近更新 更多