简体   繁体   English

Python object 字典属性被附加到每个循环迭代而不是被垃圾收集

[英]Python object with dictionary attribute being appended to with each loop iteration rather than being garbage collected

I have created an Game class which has a dictionary attribute of players as an attribute, which should have ~36 players in it.我创建了一个游戏 class ,其中包含玩家的字典属性作为属性,其中应该有大约 36 个玩家。

I am iterating though a loop, creating a new instance of a Game object with each iteration and printing the contents of each player onto a csv file.我正在迭代一个循环,每次迭代创建一个游戏 object 的新实例,并将每个玩家的内容打印到 csv 文件中。

However, with each iteration although a new object is created, it seems that the player attribute is being appended to rather than being garbage collected.然而,虽然每次迭代都会创建一个新的 object,但似乎播放器属性被附加到而不是被垃圾收集。

sheet = open('playerGames.csv', 'w+')
gameNum = 2018020001

while gameNum < 2018020015:

    game = Game(gameNum)

    print(len(game.players), end=", ")

    for player in game.players:
        for stat in game.players[player]:
            sheet.write(str(game.players[player][stat]) + ",")
        sheet.write("\n")
    game = None

    gameNum = gameNum + 1

The print statement in the above should print a number about 36 each time however it outputs the following 36, 72, 108, 144, 163, 199, 217, 253, 289, 325, 361, 397, 433, 469上面的打印语句每次应该打印一个大约 36 的数字,但是它输出以下36, 72, 108, 144, 163, 199, 217, 253, 289, 325, 361, 397, 433, 469

Should the garbage collection not clear this up?垃圾收集不应该清除这个吗? I have added the game = None statement in hopes that the entire object gets collected, however that does not seem to work.我添加了game = None声明,希望收集整个 object,但这似乎不起作用。

Given that players is defined as a global variable, you need to reset in your constructor, something like this:鉴于players被定义为全局变量,您需要在构造函数中重置,如下所示:

class Game:

    def __init__(self, n):
        players = dict()

Having a global variable is a bad practice in any language, see this .在任何语言中,使用全局变量都是一种不好的做法,请参阅this If players is a property of the Game objects you should do instead:如果 player 是Game对象的属性,则应改为:

class Game:

    def __init__(self, n):
        self.players = { }  # dictionary construction expression

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM