Get content from class list

Question:

I have 2 classes. AlchemicalStorage class is used to store the AlchemicalElement objects.

class AlchemicalElement:

    def __init__(self, name: str):
        self.name = name

    def __repr__(self):
        return f'<AE: {self.name}>'


class AlchemicalStorage:

    def __init__(self):
        self.storage_list = []

I already have a function that adds elements to AlchemicalStorage.
What I need is a function that gives an overview of the contents of the storage.

What I have so far:

def get_content(self) -> str:
    """
    Return a string that gives an overview of the contents of the storage.

    Example:
        storage = AlchemicalStorage()
        storage.add(AlchemicalElement('Fire'))
        storage.add(AlchemicalElement('Water'))
        storage.add(AlchemicalElement('Water'))
        print(storage.get_content())

    Output:
        Content:
         * Fire x 1
         * Water x 2

    The elements must be sorted alphabetically by name.
    """
    count = {}
    for e in self.storage_list:
        if e not in count:
            count[e] = 1
        else:
            count[e] += 1

The idea is that I want to create a dictionary with keys as elements and values as their amount. But instead of simple ‘Fire’ I get the representation I made (<AE: Fire>).

The question is: is there a way to get rid of "<AE: >"? Or maybe there’s an easier way to write this function without creating dictionary?

Also, I would appreciate an example of how to achieve the output string.

Asked By: fallguy

||

Answers:

it sounds kind of like you want printing out the AlchemicalStorage to have a specific format, so you could just create that format in a __str__ method:

from collections import Counter
class AlchemicalStorage:
    def __str__(self):
        # a Counter will definitely be useful for what you are trying to do
        lines = []
        for item, count in Counter(self.storage_list).items():
            lines.append(f"* {item.name} x {count}")
        return "Contents:n" + "n".join(lines)

The main thing here is instead of relying on the __repr__ method that has formatting you aren’t interested in, you can just access the .name field directly to only show the item name.

Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.