Printing attributes of objects in a class in Python

I have been studying in Python for about a month and a half, and I was wondering: is there a way to print the values โ€‹โ€‹of the variables of one class for all objects of this class? for example (I was working on a mini-game):

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 would like to be able to print a list of all potion names, but I could not find a way to do this.

+4
source share
3 answers

If you have a list of all the potions, this is simple:

potion_names = [p.name for p in list_of_potions]

If you do not have such a list, it is not so simple; you'd better maintain such a list by adding potions to the list or, better yet, a dictionary, explicitly.

You can use the dictionary to add potions when creating instances 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']
+3

.

import gc

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

You can use the class attribute to store references to all instances 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)

Then you can always access all instances:

for potion in Potion.all_potions:
+1
source

Source: https://habr.com/ru/post/1527361/


All Articles