簡體   English   中英

嘗試從函數返回字符串時,“str”對象不可調用錯誤

[英]'str' object is not callable error when trying to return a string from a function

#1
def hit_stay():
    hit_stay = ''
    while True:
        hit_stay = input('Would you like to Hit or Stay?')
        if hit_stay in ['hit','Hit','stay','Stay']:
            hit_stay = hit_stay.capitalize()
            return hit_stay
        else:
            print('Please enter a valid word)

#2
When I use the code and call the function it works the first time 
hit_stay = hit_stay()

#3
Then I print the choice
print(hit_stay)

但是,如果我再次嘗試撥打 2 以獲得不同的選擇,它會顯示“str”不可調用我試圖要求用戶進行選擇,以便稍后在我的代碼中使用該選擇。 我發現如果再次運行 1 號然后 2 號一切正常,但我需要能夠稍后調用此函數並獲得新答案。

python中的函數是“一流的”對象 您可以將函數視為任何其他變量。

因此,當您說hit_stay = hit_stay() ,變量hit_stay不再指向函數(因為您將其命名為與函數相同的名稱)。 它指向hit_stay()的結果,它是一個字符串(“HIT”或“STAY”)。

第二次嘗試調用它時,就好像您試圖“調用”一個字符串(因此出現錯誤)。

此外,作為一個建議,您可能會返回“HIT”或“STAY”,以便在您的代碼中的其他地方您將有類似的內容:

if ... == "HIT":
    # Do 'hit' stuff

您可能會發現查看enum類的內容很有用。 IMO 使其更清潔、更易於維護。 那看起來像:

from enum import Enum


class Action(str, Enum):
    HIT = "HIT"
    STAY = "STAY"


def hit_stay() -> Action:
    while True:
        action = input("Would you like to Hit or Stay?")
        try:
            return Action(action.upper())
        except ValueError:
            print("Please enter a valid word")

action = hit_stay()
if action == Action.HIT:
    # do 'hit' stuff ... 

在將其他內容[在這種特殊情況下 - 返回值] 分配給具有相同名稱的變量后,您無法再次調用該函數,例如我有一個名為 XYZ 的函數,我做了XYZ = XYZ()

現在 XYZ 將不再包含該函數,而是包含從 XYZ 返回的值,您必須將hit_stay = hit_stay()行重命名為其他內容,除了 hit_stay

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM