[英]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()
當Powershell在將'handclenched'設置為True
進入'使用劍'后帶我進入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()
作為函數調用而不是將調用/調用的代碼(這些單詞正確嗎?)作為raw_input()
分配給的secondfunction
變量secondfunction
?
在Python中,函數是對象,函數名稱只是恰好包含函數的變量。 如果您重新分配該名稱,它將不再具有您的功能。
因為您在本地范圍內重新聲明了名稱secondaction = raw_input(prompt)
。
因為您寫道:
secondaction = raw_input(prompt)
現在, sectionaction
是一個字符串,您不能像對待函數一樣調用它。 名稱不能同時具有兩種含義,並且最新的賦值具有優先權,因此您丟失了對函數的引用。 就像您在有效代碼中所做的那樣,對其中一個使用不同的名稱。
Python為什么不能將'secondaction()'讀取為函數調用,而不是調用/調用的代碼(這些單詞正確嗎?)作為'secondfunction'變量
在Python中,函數是變量。 也就是說,函數是一類對象,它們由def
語句分配給變量。 像某些語言一樣,可調用函數與可分配變量沒有單獨的命名空間。
這意味着當您編寫secondaction = raw_input(prompt)
您正在函數內部創建一個稱為secondaction
的局部變量。 現在,當您在該函數主體中的任何位置編寫secondaction
時,都將引用局部變量。 用括號編寫secondaction()
並不secondaction()
您訪問單獨的函數名稱空間,它只是嘗試調用secondaction
表示的局部變量的值,並且字符串不可調用,因此會出現錯誤。
這也意味着您可以執行以下操作:
def foo(x):
return x+1
>>> bar= foo
>>> lookup= {'thing': bar}
>>> lookup['thing']
<function foo>
>>> lookup['thing'](1)
2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.