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

时间:2015-02-04 21:12:16

标签: python function python-2.7 variables

使用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'设置为secondaction()后,Powershell将我带到True函数时,我输入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()读作函数调用而不是调用/调用的代码(那些是正确的单词?)secondfunction变量raw_input()被分配给{{1}} ?

4 个答案:

答案 0 :(得分:3)

在Python中,函数是对象,函数名只是碰巧保存函数的变量。如果您重新分配该名称,则不再保留您的功能。

答案 1 :(得分:1)

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

查看python-scopes-and-namespaces

答案 2 :(得分:1)

因为你写道:

secondaction = raw_input(prompt)

sectionaction现在是一个字符串,你不能像调用函数一样调用字符串。名称不能同时具有两个含义,并且最近的分配优先,因此您丢失了对函数的引用。正如您在有效的代码中所做的那样,为其中一个使用不同的名称。

答案 3 :(得分:0)

  

为什么Python不会读取&#39; secondaction()&#39;作为一个函数调用而不是调用/调用的代码(那些是正确的单词?)&#39; secondfunction&#39;变量

在Python中,函数变量。也就是说,函数是第一类对象,它们通过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