【问题标题】:'str' object is not callable error when trying to return a string from a function尝试从函数返回字符串时,“str”对象不是可调用错误
【发布时间】:2021-06-30 21:43:14
【问题描述】:
#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 号一切正常,但我需要能够 稍后调用此函数并获得新的答案。

【问题讨论】:

  • 在你将其他东西[在这种特殊情况下 - 返回值]分配给具有相同名称的变量之后,你不能再次调用该函数,例如我有一个名为 XYZ 的函数,我做了XYZ = XYZ();现在 XYZ 将不再包含函数,而是从 XYZ 返回的值,您必须将行重命名为 hit_stay = hit_stay() 到其他名称,而不是 hit_stay
  • @Jonathan1609 您应该将此作为答案发布。现有答案实际上并未回答问题。

标签: python-3.x string error-handling


【解决方案1】:

在您将其他东西[在这种特殊情况下-返回值]分配给具有相同名称的变量后,您不能再次调用该函数,例如我有一个名为 XYZ 的函数,我做了XYZ = XYZ()

现在 XYZ 将不再包含函数,而是从 XYZ 返回的值,您必须将行重命名 hit_stay = hit_stay() 为其他名称,除了 hit_stay 之外的任何内容

【讨论】:

    【解决方案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 ... 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-17
      • 1970-01-01
      • 2016-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-11
      相关资源
      最近更新 更多