'str' object is not callable 尝试从函数 return 字符串时出错

'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' not callable 我试图让用户做出选择,以便稍后在我的代码中使用该选择。 我发现如果 运行 数字 1 再次然后数字 2 一切正常,但我需要能够 稍后调用此函数并获得新答案。

python 中的函数是 "first-class" objects。您可以将函数视为任何其他变量。

所以,当你说 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