4

I've been messing around in Python for about a month and a half at this point, and I was wondering: is there a way to print the values of one class variables for all objects in that class? e.g. (I was working on a mini-game kinda thing):

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)

I'd like to be able to print a list of all the names of the potions, but I couldn't find a way to do that.

3 Answers3

3

If you have a list of all the potions it's simple:

potion_names = [p.name for p in list_of_potions]

If you don't have such a list, it is not so simple; you are better off maintaining such a list by adding potions to a list, or better still, a dictionary, explicitly.

You could use a dictionary to add potions to when creating instances of 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

Now you can always find all names:

all_potion_names = all_potions.keys()

and also look up potions by name:

all_potions['Freezing Potion']
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
2

You can use the garbage collector.

import gc

print [obj.name for obj in gc.get_objects() if isinstance(obj, potions)]
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
Jayanth Koushik
  • 9,476
  • 1
  • 44
  • 52
  • 2
    The garbage collector is a great debugging tool. As a general-purpose data structure for a game, not so much. You'd be looping through all objects in the current Python interpreter every time. I don't think the OP was looking for this specific route, and this should not be the advice given to a beginner. – Martijn Pieters Feb 17 '14 at 18:31
1

You could use a class attribute to hold references to all Potion instances:

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)

Then you can always access all the instances:

for potion in Potion.all_potions:
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437