为什么 Python 将我的函数调用读取为变量调用?

Why is Python reading my function call as a variable call?

使用 Python 2.7.9,这是我的代码:

    def secondaction():
        secondaction = raw_input(prompt)

        if secondaction == "walk through door" or secondaction == "go through door":
        print "Well done! You enter the Treasure Room..."
        treasure_room()

        else:
        print "If you don't go through that door you will never leave this cave."        
        secondaction()

firstact = raw_input(prompt)
global handclenched
def firstaction():
elif firstact == "use sword" and handclenched:
    print "You killed the hand giant! A door appears behind it. What will you do?"
    secondaction()

当我输入 'use sword' 并将 'handclenched' 设置为 True 后,Powershell 将我带到 secondaction() 函数时,我输入 yh 作为 raw_input() 值和 Powershell 提出此错误消息:

You killed the hand giant! A door appears behind it. What will you do?
> yh
If you don't go through that door you will never leave this cave.
Traceback (most recent call last):
  File "ex36game.py", line 168, in <module>
    right_room()
  File "ex36game.py", line 166, in right_room
    firstaction()
  File "ex36game.py", line 147, in firstaction
    firstaction()
  File "ex36game.py", line 153, in firstaction
    secondaction()
  File "ex36game.py", line 136, in secondaction
    secondaction()
TypeError: 'str' object is not callable

然而 当我将代码更改为:

 def secondaction():
    second_action = raw_input(prompt)

    if second_action == "walk through door" or second_action == "go through door":
    print "Well done! You enter the Treasure Room..."
    treasure_room()

    else:
    print "If you don't go through that door you will never leave this cave."        
    secondaction()

一切正常,我没有收到任何错误消息。

为什么 Python 不能将 secondaction() 读取为函数调用,而不是将 invokes/calls(这些词正确吗?) secondfunction 变量的代码读取raw_input() 被分配给?

因为您在本地范围内重新声明了名称 secondaction = raw_input(prompt)

看看python-scopes-and-namespaces

因为你写道:

secondaction = raw_input(prompt)

sectionaction 现在是一个字符串,您不能像调用函数一样调用字符串。一个名字不能同时有两种含义,最近的赋值优先,所以你失去了对你的函数的引用。为其中之一使用不同的名称,就像您在有效代码中所做的那样。

在Python中,函数是对象,函数名只是一个恰好持有函数的变量。如果您重新分配该名称,它将不再保留您的功能。

Why can't Python read the 'secondaction()' as a function call instead of code that invokes/calls (are those the correct words?) the 'secondfunction' variable

在Python中,函数变量。也就是说,函数是first-class对象,通过def语句赋值给变量;可调用函数与可赋值变量没有单独的命名空间,就像某些语言那样。

这意味着当您编写 secondaction = raw_input(prompt) 时,您正在函数内部创建一个名为 secondaction 的局部变量。现在,当您在该函数体中的任何地方编写 secondaction 时,您指的是局部变量;用括号写 secondaction() 不会让你访问一个单独的函数命名空间,它只是试图调用 secondaction 代表的局部变量的值,并且字符串不可调用所以你得到一个错误.

这也意味着您可以执行以下操作:

def foo(x):
    return x+1

>>> bar= foo
>>> lookup= {'thing': bar}
>>> lookup['thing']
<function foo>
>>> lookup['thing'](1)
2