2012-03-27 11 views
1

編輯:已解決。感謝幫助的人,但看起來問題在於列表被覆蓋並轉換爲精靈組,導致所有列表操作無用。從列表中刪除未引用的對象

我最近開始在Python編程(總是襯托警鐘),所以我道歉,如果我編寫做事的方式略有嚇人。這個特定程序導入pygame(使用'引擎')。

我試圖創建一個包含對象/精靈的列表。但是,我似乎已經實現了,不再需要時,從列表中刪除對象時出現問題,因爲對象沒有特定的指針,據我所知。

精靈類的構造如下;

class Point(pygame.sprite.Sprite): 
    def __init__(self,pos=(0,0)): 
     pygame.sprite.Sprite.__init__(self) 

     #Unimportant code 

     self.dead=False 
     print self 
     #This prints; "<Point sprite(in 0 groups)>" 

    def update(self): 
     if(self.dead): 
      #sprList_PointSet.remove(?) 
      pass 

創建對象和列表;

sprList_PointSet=[] 
sprList_PointSet+=[Point((50,90))] 
sprList_PointSet+=[Point((65,110))] 
# ... 

print sprList_PointSet 
#This prints; [<Point sprite(in 0 groups)>, <Point sprite(in 0 groups)>, ...] 

有一種方法,以從列表中刪除實例時在其中不存在明顯的存儲器指示符的情況下,使用卸下襬臂(x)時不再需要了嗎?如果沒有/或/和可以有人推薦一個更好的方式來做到這一點。

+0

您可以使用'lst.remove(self)',但是您需要對類內部列表的引用。 – 2012-03-27 20:11:02

+0

@NiklasB。如果'sprList_PointSet'是一個全局變量,只要他不嘗試設置它,他就可以很好地引用它。 – agf 2012-03-27 20:12:20

+0

@agf:不過,如果不是,那會更好。 – 2012-03-27 20:16:50

回答

2

self點,你要刪除的對象,所以才remove(self)

def update(self): 
    if self.dead: 
     try: 
      sprList_PointSet.remove(self) 
     except ValueError: 
      pass 

removemutable sequences定義和描述in the tutorial

Remove the first item from the list whose value is x. It is an error if there is no such item.

+0

不幸的是,這是我第一次嘗試。它返回錯誤; 「ValueError:list.remove(x):x不在列表中」 – H3katonkheir 2012-03-27 20:29:29

+0

@ H3katonkheir然後在不在列表中的對象上調用update。你需要處理錯誤。 – agf 2012-03-27 20:32:18

+0

該對象在列表中,當我「打印」列表時,它顯示那裏有東西,但沒有顯示任何好的參考。表明; 「<點精靈(0組)>」每個對象。 – H3katonkheir 2012-03-27 20:37:16

2

您可以使用weak references讓一個實例消失時,沒有什麼「重要」需要它了。

+0

優雅的解決方案 – pylover 2012-03-27 20:27:15

+0

我不明白爲什麼這將是必要的,在這種特殊情況下。你能詳細說明嗎? – 2012-03-27 20:31:35

+0

是的,我認爲在這種情況下,我們的想法是讓他們脫離列表,不允許他們被垃圾收集 - 他仍然必須用'weakref'從列表中刪除死亡引用。 – agf 2012-03-27 20:36:48