【问题标题】:Printing Attributes of Objects in a Class in Python [duplicate]在Python中打印类中对象的属性[重复]
【发布时间】:2014-02-17 18:25:04
【问题描述】:

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

我希望能够打印一份所有药水名称的列表,但我找不到这样做的方法。

【问题讨论】:

    标签: python class object attributes


    【解决方案1】:

    如果你有一份所有药水的清单,那很简单:

    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']
    

    【讨论】:

      【解决方案2】:

      您可以使用垃圾收集器。

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

      【讨论】:

      • 垃圾收集器是一个很棒的调试工具。作为游戏的通用数据结构,并没有那么多。您每次都将遍历当前 Python 解释器中的所有对象。我不认为 OP 正在寻找这条特定的路线,这不应该是给初学者的建议。
      【解决方案3】:

      您可以使用类属性来保存对所有 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:
      

      【讨论】:

        猜你喜欢
        • 2018-06-28
        • 2013-07-11
        • 2011-08-23
        • 2018-09-27
        • 2016-03-21
        • 2010-10-25
        • 2016-03-14
        • 1970-01-01
        • 2013-07-30
        相关资源
        最近更新 更多