找不到要删除对象的列表

2024-09-28 05:25:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚刚开始一个练习,我应该完成一个基本的'愤怒的小鸟'克隆。 我被困在一个点,我想从列表中删除一个对象。该列表包含游戏中使用的所有障碍(框)。 所以如果我想在一个盒子被击中后移除它,我必须制定一个方法来做到这一点。不管我怎么做都失败了。你知道吗

class spel(object):
    def __init__(self):        
        self.obstacles = [obstacle(50,pos=(200,90)),]
  #defines all other stuff of the game

class obstacle(object):
    def __init__(self,size,pos):
   #defines how it looks like

    def break(self):
      #methode that defines what happens when the obstacles gets destroyed
        spel.obstacles.remove(self)

我得到的错误是:

 AttributeError: 'NoneType' object has no attribute 'obstacles'

在最后一行之后。 请原谅我的noob级别,但关键是我以后再也不需要编写代码了,所以没有必要解释一切。你知道吗


Tags: the对象posself游戏列表objectinit
3条回答

您还没有实例化spel类。你知道吗

如果你想使用这样的类,你必须对它进行初始化(创建一个实例)。你知道吗

在这样的课堂之外:

app = spel() # app is an arbitrary name, could be anything

然后你可以这样调用它的方法:

app.obstacles.remove(self)

或者在你的情况下,从另一个班级:

self.spel = spel()

self.spel.obstacles.remove(self)

我提议如下:

class spel(object):
    obstacles = []
    def __init__(self,size,pos):        
        spel.obstacles.append(obstacle(size,pos))
        #defines all other stuff of the game

class obstacle(object):
    def __init__(self,size,pos):
        self.size = size
        self.pos = pos
    def brak(self):
        #methode that defines what happens when the obstacles gets destroyed
        spel.obstacles.remove(self)

from pprint import pprint

a = spel(50,(200,90))
pprint( spel.obstacles)
print

b = spel(5,(10,20))
pprint( spel.obstacles )
print

c = spel(3,None)
pprint( spel.obstacles )
print

spel.obstacles[0].brak()
pprint( spel.obstacles )

返回

[<__main__.obstacle object at 0x011E0A30>]

[<__main__.obstacle object at 0x011E0A30>,
 <__main__.obstacle object at 0x011E0B30>]

[<__main__.obstacle object at 0x011E0A30>,
 <__main__.obstacle object at 0x011E0B30>,
 <__main__.obstacle object at 0x011E0AF0>]

[<__main__.obstacle object at 0x011E0B30>,
 <__main__.obstacle object at 0x011E0AF0>]

您已将“spel”定义为类,而不是对象。因此,您收到了一个错误,因为Python正在尝试查找spel类的成员“障碍物”,在运行单个spel对象的__init__方法之前,该成员不存在。你知道吗

要将spel类的对象与创建的每个单独的障碍相关联,可以尝试为障碍类的对象指定一个引用其关联的spel对象的数据成员。数据成员可以在障碍类__init__函数中实例化。像这样:

class obstacle(object):
    def __init__(self, spel, size, pos):
        self.spel = spel
        #etc

    def break(self):
        self.spel.obstacles.remove(self)

希望有帮助。你知道吗

相关问题 更多 >

    热门问题