无法删除 class 的实例

Can't remove instances of a class

我开始在 python 中编写代码并使用 pyzero 制作一个简单的游戏。游戏结束后,我想删除某些类型classes的所有现有实例,让游戏重新开始。我有一个 class 的所有实例的列表,但是使用 remove(self) 似乎会导致我无法解决的逻辑问题。

class Ball(Actor):
    ball_list = []

    def __init__(self, actor):               
        Actor.initiate_actor(self,"ball")
        Ball.ball_list.append(self)
        self.alive = True

    def kill(self):
        if self.alive:
            self.alive = False
            Ball.ball_list.remove(self) 


def new_game():
    global game_over, score

    for actor in Ball.ball_list:
        actor.kill()

    score = 0
    game_over = False


def draw():
    global game_over
    if game_over:
        screen.clear()
        screen.draw.text("Game Over", center = (WIDTH/2, HEIGHT/2), color = 'white')

    else:
        screen.clear()
        backdrop.draw()  
        for actor in Ball.ball_list:
            if actor.alive:
                actor.draw()

实际上,您是在遍历列表时从列表中删除对象。阅读 How to remove items from a list while iterating?,了解有关此主题的更多信息。

创建列表的浅表副本(Ball.ball_list[:],请参阅 More on Lists)并遍历列表的副本,同时从原始列表中删除项目:

def new_game():
    global game_over, score

    for actor in Ball.ball_list[:]:
        actor.kill()

    score = 0
    game_over = False

无论如何,既然你想从列表中删除所有元素,调用 clear()

就足够了
Ball.ball_list.clear()

或删除所有元素(参见del

del Ball.ball_list[:]

分别新建一个空列表

Ball.ball_list = []

请注意,未使用的对象的内存由 garbage collection 释放,因此从(所有)列表中删除一个对象就足够了。此外,没有必要重置 将被销毁的对象的属性。