我为什么无法调用这个列表?
我正在尝试从一个模块中导入一个列表,但出现了这个错误:
错误追踪(最近的调用在前): 文件 "main.py",第 8 行,在 words_list = hangman_words.word_list() 类型错误:'list' 对象不可调用
这是我的代码:
#Step 5
import hangman_words
import hangman_art
import random
#TODO-1: - Update the word list to use the 'word_list' from hangman_words.py
#Delete this line: word_list = ["ardvark", "baboon", "camel"]
words_list = hangman_words.word_list()
chosen_word = random.choice(words_list)
word_length = len(chosen_word)
end_of_game = False
lives = 6
#TODO-3: - Import the logo from hangman_art.py and print it at the start of the game.
print(hangman_art.logo)
#Testing code
print(f'Pssst, the solution is {chosen_word}.')
#Create blanks
display = []
for _ in range(word_length):
display += "_"
while not end_of_game:
guess = input("Guess a letter: ").lower()
#TODO-4: - If the user has entered a letter they've already guessed, print the letter and let them know.
if guess in display:
print(f"You've already guessed {guess}")
#Check guessed letter
for position in range(word_length):
letter = chosen_word[position]
print(f"Current position: {position}\n Current letter: {letter}\n Guessed letter: {guess}")
if letter == guess:
display[position] = letter
#Check if user is wrong.
if guess not in chosen_word:
#TODO-5: - If the letter is not in the chosen_word, print out the letter and let them know it's not in the word.
print(f"You guessed {guess}, that is not in the word. You lose a (1) life")
lives -= 1
if lives == 0:
end_of_game = True
print("You lose.")
#Join all the elements in the list and turn it into a String.
print(f"{' '.join(display)}")
#Check if user has got all letters.
if "_" not in display:
end_of_game = True
print("You win.")
#TODO-2: - Import the stages from hangman_art.py and make this error go away.
print(hangman_art.stages[lives])
我试着把它放在一个变量里,正如你在我的代码中看到的,但结果还是出现了完全相同的错误。
2 个回答
0
我觉得你可能是把hangman_words.word_list()当成一个函数来用,而实际上它是一个列表。你只需要去掉括号,就可以这样写:
words_list = hangman_words.word_list
希望这能帮到你,谢谢!
0
看起来 hangman_words.word_list
是一个 list
(列表)。在Python中,列表是不能像函数那样被调用的。
替代方案 1:
如果你的目标是获取指向 hangman_words
中提到的列表的引用,你可以这样做:
在 hangman_words.py
文件中:
word_list = ['all', 'words', 'you', 'have']
在你的脚本中:
from hangman_words import word_list
print(word_list)
结果是: ['all', 'words', 'you', 'have']
替代方案 2:
如果你需要对你的列表进行某些操作,或者想确保不改变原始列表,你可以使用一个函数来获取原始列表的副本。可以这样做:
在 hangman_words.py
文件中:
import copy
__word_list = ['all', 'words', 'you', 'have']
def get_word_list():
return copy.deep_copy(__word_list)
在你的脚本中:
from hangman_words import get_word_list
print(get_word_list())
结果是: ['all', 'words', 'you', 'have']