在 del、none、[] 之后列出保留数据



我正在构建一个简短的游戏(用于一个研究项目(。该游戏旨在在Python Shell(使用3.6.1(中运行。

我遇到的问题是"退出"(退出游戏(。如果用户在输入提示期间键入"退出",游戏将退出。该功能很好,但是如果用户重新启动游戏,则用于保存用户数据的列表将保持填充状态。清空列表至关重要,我尝试设置列表 = [] 和列表 = NONE,但都没有清空列表。什么给?

下面是代码的精简版本:

import sys
class Game(object):
myList = [] #init list
def inflate_list(self):
for x in range(0, 10):
self.myList.append([x]) #just putting x into the list (as example)
print(self.myList)
self.run_game()
def check_user_input(self, thisEntry):
try:
val = int(thisEntry)#an integer was entered
return True
except ValueError: #needed because an error will be thrown
#integer not entered
if thisEntry == "quit":
#user wants to quit
print("..thanks for playing")
#cleanup
self.thisGame = None
self.myList = []
del self.myList
print("..exiting")
#exit
sys.exit()
else:
print("Invalid entry. Please enter a num. Quit to end game")
return False    
def run_game(self):
#init
getUserInput = False
#loop
while getUserInput == False:
#check and check user's input
guess = input("Guess a coordinate : ")
getUserInput = self.check_user_input(guess)
print (guess, " was entered.")
#start game
thisGame = Game()
thisGame.inflate_list()

运行示例

>>>thisGame = Game()
>>>thisGame.inflate_list()
[[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]]
Guess a coordinate : aaaaa
Invalid entry. Please enter a coordinate. Quit to end game
aaaaa  was entered.
Guess a coordinate : quit
..thanks for playing
..exiting
>>>thisGame = Game()
>>>thisGame.inflate_list()
[[0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [0], [1], [2], [3], [4], [5], [6], [7], [8], [9]]
Guess a coordinate : 

游戏第二次启动时,列表仍然包含数据。

更改此行:

myList = [] #init list

对此:

def __init__(self):
self.myList = [] #init list

(修复后,不需要任何"清理"。

正如@JoshLee上面的评论中指出的那样,这个堆栈溢出问题是了解类属性和实例属性之间区别的好地方:Python 类成员。

最新更新