用Python打印类中对象的属性

时间:2014-02-17 18:25:04

标签: python class object attributes

此时我已经在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)

我希望能够打印出所有药水名称的清单,但我找不到办法做到这一点。

3 个答案:

答案 0 :(得分: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 :(得分:2)

您可以使用垃圾收集器。

import gc

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

答案 2 :(得分:1)

您可以使用class属性来保存对所有Potion个实例的引用:

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:
相关问题