2013-12-14 58 views
1

我剛開始練習,我應該完成一個基本的「憤怒的小鳥」克隆。 我被困在我想從列表中刪除對象的地方。該列表包含遊戲中使用的所有障礙物(框)。 所以如果我想刪除一個盒子後,我必須做一個方法來做到這一點。無論我如何做,這都會失敗。找不到列表以刪除對象

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級別,但重要的是,我不會再需要在此之後再次編碼,所以不需要解釋所有內容。

回答

0

您已將'spel'定義爲類,而不是對象。因此,您收到了一個錯誤,因爲Python正在嘗試查找spel類的成員'障礙',而這在運行單個spel對象的方法之前並不存在。

要將spel類的對象與創建的每個障礙物關聯起來,您可以嘗試爲障礙類的對象提供引用其關聯的spel對象的數據成員。數據成員可以在障礙類「__init__」函數中實例化。像這樣:

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

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

希望有所幫助。

+2

也不使用break作爲方法名稱,它是一個保留字 – M4rtini

+0

謝謝。錯過了。 – andreipmbcn

+0

謝謝! @ M4rtini我用荷蘭語寫了遊戲,所以它是'breek'。我只是很快將其翻譯爲可讀性... –

0

你還沒有實例化spel類。

如果你想使用這樣的類,你必須對它進行類型化(創建一個實例)。一類

外,像這樣:

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

那麼你會調用它的方法是這樣的:

app.obstacles.remove(self) 

或者在你的情況下,從另一個類中:

self.spel = spel() 

self.spel.obstacles.remove(self) 
+0

我知道,我只是沒有這一切都添加到我的職位(遺憾的是目前還不清楚) –

+0

確定,但這是與您接受的答案相同 – Totem

0

我提出以下幾點建議:

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>] 
+0

謝謝,但解決方案@andreipmbcn給了我的是我應該做的。不過看到你的是很有趣的,因爲我不知道你可以在「def__init__」之前放置東西, –