簡體   English   中英

在Python中無法調用Str對象?

[英]Str object not callable in Python?

我正在嘗試制作一個簡單的魔術八球程序,該程序會問一個問題,給出一個隨機響應,然后提示用戶是否要重試。 一切都進行到“再次詢問”部分,在那里所有地獄都崩潰了,並出現此錯誤:

TypeError:“ str”對象不可調用

我對Python還是很陌生,說實話我可能只是犯了一個菜鳥錯誤,但是尋求我所相信的幫助並沒有什么可恥的。

這是代碼:

def question():
    question = str(input("Ask a yes or no question: "))

    replies = ["It is certain",
     "It is decidedly so",
     "Without a doubt",
     "Yes definitely",
     "You may rely on it",
     "As I see it, yes",
     "Most likely",
     "Outlook good",
     "Yes",
     "Signs point to yes",
     "Reply hazy try again",
     "Ask again later",
     "Better not tell you now",
     "Cannot predict now",
     "Concentrate and ask again",
     "Don't count on it",
     "My reply is no",
     "My sources say no",
     "Outlook not so good",
     "Very doubtful",
               ]

    rand_num = random.randint(0, 20)

    print(replies[rand_num])

    def ask_again():
        again = input("Would you like to ask another question? (Y/N): ")
        if again == "Y" or "y":
            question()
        elif again == "N" or "n":
            print("Thank you and goodbye.")
        else:
            print("That is not an acceptable answer.")
            ask_again()
    ask_again()
question()
def question(): # <<<<< here you define `question` as the function
    question = str(input("Ask a yes or no question: ")) # <<< and here you "shadow" that with a string (see below the long explanation).

然后,稍后在函數定義中:

def ask_again():
        again = input("Would you like to ask another question? (Y/N): ")
        if again == "Y" or "y":
            question() # <<< here, question is not a function anymore because you redefined the name `question` to a string on the second line of the function definition

這是怎么回事?

當你def的功能question()你基本上是定義一個名為對象question與您的函數的代碼相關聯。 但是,在函數定義中,要做的第一件事是重新定義對象question ,並為其分配一個字符串。 這意味着在函數定義范圍內 ,當您使用question您不再指的是函數,而是指分配給該對象的字符串。

因此,當您在我上面標記的行中的定義內進行question()時出現錯誤。 此時,您不是在調用函數,而是嘗試“調用”字符串,這會引起錯誤。

注意:在函數question的定義之外,調用question()實際上會運行該函數,因為僅在函數定義的范圍內對對象進行了陰影處理。

暫無
暫無

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

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