【问题标题】:Calling a method with a string and input()使用字符串和 input() 调用方法
【发布时间】:2013-09-16 13:26:00
【问题描述】:

我正在复习我的 Python,但我对某些事情有些困惑,以下代码无法按预期工作:

def a():
    print "called a"

def b():
    print "called b"

dispatch = {'go':a, 'stop':b}
dispatch[input()]()

当我在控制台中输入单词 go 时,我得到“NameError: name 'go' is not defined”,但是当我输入 'go'(带引号)时它工作正常。 input() 不返回字符串吗?如果不是,那么不应该使用 str() 将输入转换为字符串吗?

当我将代码更改为:

dispatch[(str(input())]()

我仍然得到相同的行为。

注意:我使用的是 Python2.7,如果它有所作为的话。

对不起,如果这很明显,我已经有几年没有使用 Python了!

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    input() 在 Python 2.7 中相当于:

    eval(raw_input())
    

    因此,您应该在 python 2.7 中使用 raw_input() 以避免此类错误,因为它不会尝试 evaluate 给定的输入。

    由于您添加了引号,Python 将其解释为字符串。

    另外,请注意raw_input() 将返回一个字符串,因此围绕它调用str() 是没有意义的。


    请注意,在 Python 3 中,input() 的行为类似于 Python 2.7 中的 raw_input()

    【讨论】:

    • 我阅读了 2.X 和 3.X 之间更“显着”变化的列表,但没有列出,谢谢!
    • @NickBoudreau 嗯,这是在哪里?如果您想查看的话,docs 上有一个很棒的列表:)
    • 我不记得那个网站了,我认为它只是某人的博客,但我写下了他们列出的更改:字符串现在是 unicode,print 是一个函数而不是语句,范围被删除和替换为 xrange,整数除法产生浮点数,所有类现在都是新样式。感谢您的链接,非常有用!
    【解决方案2】:

    你想要raw_input()input() 将用户的输入评估为 Python 代码。

    【讨论】:

      【解决方案3】:

      使用raw_input()input() 等价于 eval(raw_input()),所以当你输入不带引号的 go 时,python 会尝试 eval go 并失败。使用引号,它 eval 是字符串(即返回它),它将用于索引您的 dict。

      raw_input 适用于任何情况。

      【讨论】:

        【解决方案4】:

        你也可以这样用:

        def go():
            print "called a"
        
        
        def stop():
            print "called b"
        
        input()()  # Equivalent to eval(raw_input())()
        # OR
        my_function = input()
        my_function()  # Might be easier to read
        
        # Another way of doing it:
        
        val = raw_input()
        globals()[val]()
        

        【讨论】:

          猜你喜欢
          • 2012-06-22
          • 2011-04-25
          • 1970-01-01
          • 2012-03-01
          • 1970-01-01
          • 2014-01-03
          • 1970-01-01
          • 2023-03-29
          • 1970-01-01
          相关资源
          最近更新 更多