python - 在del,none,[]之后列出保存数据

时间:2017-07-07 02:35:49

标签: python python-3.x

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

我遇到的问题是“退出”(退出游戏)。如果用户在输入提示期间键入“退出”,则退出游戏。功能很好,但是如果用户比RESTARTS游戏,用于保存用户数据的列表仍然填充。列表清空是至关重要的,我尝试设置list = []和list = 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 : 

游戏第二次启动时,列表仍保留数据....

1 个答案:

答案 0 :(得分:1)

更改此行:

myList = [] #init list

到此:

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

(在修复之后,不需要“清理”。)

正如@JoshLee在上面的评论中所指出的,这个Stack Overflow问题是了解类属性和实例属性之间差异的好地方:Python Class Members