2014-02-17 24 views
4

在這一點上,我一直在Python中弄亂了大約一個半月的時間,我在想:是否有一種方法可以爲所有人打印一個類變量的值該類中的對象?例如(我工作的一個小遊戲有點事):打印Python中的類中對象的屬性

class potions: 

    def __init__(self, name, attribute, harmstat, cost): 
      self.name = name 
      self.attribute = attribute 
      self.harmstat = harmstat 
      self.cost = cost 

Lightning = potions("Lightning Potion", "Fire", 15, 40.00) 

Freeze = potions("Freezing Potion", "Ice", 20, 45.00) 

我希望能夠打印魔藥的所有名稱的列表,但我無法找到一個方法來做到這一點。

回答

2

您可以使用垃圾回收器。

import gc 

print [obj.name for obj in gc.get_objects() if isinstance(obj, potions)] 
+2

垃圾收集器是一個偉大的調試工具。作爲一款遊戲的通用數據結構,並非如此。您每次都會循環瀏覽當前Python解釋器中的所有對象。我不認爲OP正在尋找這條具體路線,這不應該是給初學者的建議。 –

3

如果你把所有的魔藥的清單很簡單:

potion_names = [p.name for p in list_of_potions] 

如果你沒有這樣的列表,它不是那麼簡單;你最好是通過向列表添加藥劑,或者更好地在字典中添加藥劑來更好地維護這樣的列表。

你可以使用字典藥水加創造的potions實例時:

all_potions = {} 

class potions:  
    def __init__(self, name, attribute, harmstat, cost): 
     self.name = name 
     self.attribute = attribute 
     self.harmstat = harmstat 
     self.cost = cost 
     all_potions[self.name] = self 

現在,你總是可以找到所有名稱:

all_potion_names = all_potions.keys() 

,並通過名稱來查找藥水:

all_potions['Freezing Potion'] 
1

您可以使用class屬性來保存對所有的引用個實例:

class Potion(object): 

    all_potions = [] 

    def __init__(self, name, attribute, harmstat, cost): 
     self.name = name 
     self.attribute = attribute 
     self.harmstat = harmstat 
     self.cost = cost 
     Potion.all_potions.append(self) 

那麼你可以隨時訪問所有的實例:

for potion in Potion.all_potions: