python-在del之后列出保持数据,无,[]
我正在制作一个短游戏(用于学习项目)。游戏将在Python Shell中运行(使用3.6.1) 我遇到的问题是“退出”(退出游戏)。如果用户在输入提示中键入“退出”,则游戏退出。功能正常,但是如果用户重新启动游戏,则用于保存用户数据的列表仍会填充。清空列表非常重要,我尝试设置list=[]和list=NONE,但都没有清空列表。有什么好处 下面是代码的浓缩版本:python-在del之后列出保持数据,无,[],python,python-3.x,Python,Python 3.x,我正在制作一个短游戏(用于学习项目)。游戏将在Python Shell中运行(使用3.6.1) 我遇到的问题是“退出”(退出游戏)。如果用户在输入提示中键入“退出”,则游戏退出。功能正常,但是如果用户重新启动游戏,则用于保存用户数据的列表仍会填充。清空列表非常重要,我尝试设置list=[]和list=NONE,但都没有清空列表。有什么好处 下面是代码的浓缩版本: import sys class Game(object): myList = [] #init list def inflate
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在上面的评论中指出的,这个堆栈溢出问题是了解类属性和实例属性之间区别的好地方:。试试
self.myList.clear()
。可能是重复的谢谢,我会试试。。。不,列表中仍然包含数据…谢谢smarx。那起作用了。。。。那么,有没有关于为什么一个成员变量(在类中)在将该变量放入init方法时保存数据(甚至在删除等之后)会产生预期的功能的评论?读取类属性与实例属性之间的差异